码迷,mamicode.com
首页 > Web开发 > 详细

我的第一个Go web程序 纪念一下

时间:2018-03-22 01:39:32      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:func   server   两种   函数名   nbsp   指针   http   log   amp   

参考Go web编程,很简单的程序:

  大致的步骤:

    1. 绑定ip和端口
    2. 绑定对应的处理器或者处理器函数,有下面两种选择,选择一种即可监听ip及端口
      1. 处理器:
        1. 定义一个struct结构体
        2. 然后让这个结构体实现ServeHTTP的接口
        3. 创建一个该结构的实例
        4. 将该实例的地址(指针)作为参数传递给Handle
      2. 处理器函数
        1. 定义一个函数
        2. 该函数必须和ServeHTTP一样的函数签名
        3. 函数名直接作为参数传递给HandleFunc
    3. 访问绑定的ip加port

 使用处理器形式:

package main
import (
	"fmt"
	"net/http"
)
type Home struct{}
type About struct{}
func (h *Home) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "this is home")
}
func (a *About) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "this is about")
}
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	home := &Home{}
	about := &About{}
	http.Handle("/home", home)
	http.Handle("/about", about)
	server.ListenAndServe()
}

  

使用处理器函数形式:

package main
import (
	"fmt"
	"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "this is home2")
}
func about(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "this is about2")
}
func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/home", home)
	http.HandleFunc("/about", about)
	server.ListenAndServe()
}

  

我的第一个Go web程序 纪念一下

标签:func   server   两种   函数名   nbsp   指针   http   log   amp   

原文地址:https://www.cnblogs.com/-beyond/p/8620813.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!