如何用go来建立web服务

安装go

mac安装

brew install golang

配置环境变量:vi ~/.bash_profile 或 vi /etc/profile

  1. export GOROOT=/usr/local/go     //安装目录
  2. export GOPATH=$GOROOT/bin  //工作区(即工作目录),可以配置多个,以:分割
  3. export PATH=$PATH:$GOPATH   //以:分割

使生效:source ~/.bash_profile  或  source /etc/profile

确认是否生效:go version

编译测试文件:go build test.go

运行测试文件:go run test.go

centos安装

下载:wget https://dl.google.com/go/go1.11.5.linux-amd64.tar.gz

解压:tar -C /usr/local -zxvf  go1.11.5.linux-amd64.tar.gz

环境变量:vi /etc/profile

追加:export GOROOT=/usr/local/go

           export PATH=$PATH:$GOROOT/bin

生效:source /etc/profile

确认:go version

 

Web服务

Go语言里面提供了一个完善的net/http包,通过http包可以很方便的就搭建起来一个Web服务。

同时使用这个包能很简单地对Web的路由,静态文件,模版,cookie等数据进行设置和操作。

Go不需要nginx、apache服务器,因为他直接就监听tcp端口,做了nginx做的事情。

form.go
package main

import (

  "fmt"

  "net/http"

  "html/template"

  "log"

  "database/sql"

   _ "github.com/go-sql-driver/mysql"

)

func main() {

 http.HandleFunc("/login",login)

  err := http.ListenAndServe(":9093",nil)

  if err != nil {

    log.Fatal("ListenAndServe: ",err)

  }

}

func login(w http.ResponseWriter, r *http.Request) {

  fmt.Println("method:", r.Method)

  r.ParseForm()

  if r.Method == "GET" {

     t, _ := template.ParseFiles("login.gtpl")

    t.Execute(w, nil)

  } else {

    fmt.Println("username:", r.Form["username"])

    fmt.Println("password:", r.Form["password"])

    var user=r.Form["username"]

    var pwd=r.Form["password"]

    result, err:= check(user,pwd)

     if result {

        t, _ := template.ParseFiles("home.gtpl")

        t.Execute(w, nil)

    }

  }

}

func check(username,password string) bool {

  db, err := sql.Open("mysql", "root:@/leia")

  checkErr(err)

  rows,err := db.Query("SELECT pwd FROM tbl_test WHERE name=?",username)

  checkErr(err)

  for rows.Next() {

       var pwd string

       rows.Columns()

       err = rows.Scan(&pwd)

       checkErr(err)

       if(pwd == password) {

         fmt.Println("login success!")

          return true

       }
  }

}

login.gtpl

 

mysql

go get "github.com/go-sql-driver/mysql"

 

beego框架

$ go get github.com/astaxie/beego (源码)
$ go get github.com/beego/bee (bee开发工具)
$ cd $GOPATH/src
$ bee new hello

 

退出服务

control+c 即可

package main
import "fmt"
import "os"
import "os/signal"
import "syscall"
func main() {
    // Go signal notification works by sending `os.Signal`
    // values on a channel. We'll create a channel to
    // receive these notifications (we'll also make one to
    // notify us when the program can exit).
    sigs := make(chan os.Signal, 1)
    done := make(chan bool, 1)
    // `signal.Notify` registers the given channel to
    // receive notifications of the specified signals.
    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
    // This goroutine executes a blocking receive for
    // signals. When it gets one it'll print it out
    // and then notify the program that it can finish.
    go func() {
        sig := <-sigs
        fmt.Println()
        fmt.Println(sig)
        done <- true
    }()
    // The program will wait here until it gets the
    // expected signal (as indicated by the goroutine
    // above sending a value on `done`) and then exit.
    fmt.Println("awaiting signal")
    <-done
    fmt.Println("exiting")
}

go run main.go执行这个程序,敲入ctrl-C会发送SIGINT信号。 此程序接收到这个信号后会打印退出。

 

页面注入动态数据

    后台传数据的写法如下:

import "html/template"

titles := []string{"title1","title2"}

t, _ := template.ParseFiles("views/tasks.gtpl")

t.Execute(w,titles)

    页面中要遍历titles的话写法如下:

{{range .}}

<dd><a href="#" >{{.}}</a></dd>

{{end}}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值