zoukankan      html  css  js  c++  java
  • Go 学习笔记(一)

    随着Go的应用越来越火热,自己也终于开始学习了。平时经常用C,看着Go还是比较亲切的。好了,开始。

    今天主要是按照书上的内容自己简单的实践了下最基本的输出,以及网页功能,上代码:

    1 package main
    2 
    3 import (
    4     "fmt"
    5 )
    6 
    7 func main() {
    8     fmt.Printf("Hello world
    ")
    9 }

    加法运算代码:

     1 package main
     2 
     3 import (
     4     "fmt"
     5 )
     6 
     7 func add(a int,b int)(c int){
     8     c= a+b
     9     return c
    10 }
    11 
    12 
    13 func main() {
    14     c:=add(1,2)
    15     fmt.Println(c)
    16 }

    网页“Hello world”代码:

     1 package main
     2 
     3 import (
     4     "fmt"
     5     "net/http"
     6 )
     7 func sayHelloName(w http.ResponseWriter,r *http.Request){
     8     fmt.Fprintf(w,"hello,world")
     9 
    10 }
    11 
    12 func main() {
    13 
    14     http.HandleFunc("/",sayHelloName)
    15 }

    登录截图:

    网页登录代码:

     1 package main
     2 
     3 import (
     4     "fmt"
     5     "html/template"
     6     "net/http"
     7     "log"
     8 )
     9 
    10 func login(w http.ResponseWriter,r* http.Request){
    11 
    12     fmt.Println("method:", r.Method)
    13     if r.Method == "GET"{
    14         t,_:=template.ParseFiles("/Users/mac/IdeaProjects/go1/login.gtpl")
    15         t.Execute(w,nil)
    16     }else{
    17         r.ParseForm()
    18         fmt.Println("username:",r.Form["username"])
    19         fmt.Println("password",r.Form["password"])
    20     }
    21 }
    22 
    23 func main() {
    24     http.HandleFunc("/login",login)
    25     err:=http.ListenAndServe(":9090",nil)
    26     if err != nil {
    27         log.Fatal("ListenAndServe: ", err)
    28     }
    29 }

    运行结果截图:

    consle截图:

    这里需要注意的是,程序在Mac环境下,网页模板路径需要使用

    绝对路径“/Users/mac/IdeaProjects/go1/login.gtpl” ,不然会报如下错误:

    runtime error: invalid memory address or nil pointer dereference goroutine 5 

     

  • 相关阅读:
    vue-slot插槽
    js中filter函数
    js异步处理
    js变量提升
    js中的4种函数调用模式
    js方法
    Javascript中的闭包 O__O "…
    js实现瀑布流以及加载效果
    2D转换下的zoom和transform:scale的区别
    [转]JavaScript与元素间的抛物线轨迹运动
  • 原文地址:https://www.cnblogs.com/ibyte/p/5742940.html
Copyright © 2011-2022 走看看