go web相关实例记录

  1. http服务器demo实例:
package main

import (
	"fmt"
	"log"
	"net/http"
)

func sayHello(w http.ResponseWriter, r * http.Request)  {
	r.ParseForm()   //解析参数
	fmt.Println("Form", r.Form)
	fmt.Println("method: ", r.Method)
	fmt.Println("scheme: ", r.URL.Scheme)
	fmt.Println("Path: ", r.URL.Path)
	fmt.Println("UserAgent: ", r.UserAgent())

	for k, v := range r.Form{
		fmt.Println("key: ", k)
		fmt.Println("v: ", v)
	}
	fmt.Fprintf(w, "hello world")

}

func main() {
	http.HandleFunc("/", sayHello)

	err :=  http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe", err)

	}
}


请求
#curl 127.0.0.1:8080                                                                                                       ✔
hello world%

输出:
 #go run goweb_demo01.go                                                                                     1 ↵
Form map[]
method:  GET
scheme:  
Path:  /
UserAgent:  curl/7.54.0

  1. 用户自定义路由
package main

import (
	"fmt"
	"net/http"
)

// User define ropute
type MyMux struct {
}

func (p *MyMux)ServeHTTP(w http.ResponseWriter, r *http.Request)  {
	if r.URL.Path == "/"{
		sayHelloRoute(w, r)
		return
	}
	http.NotFound(w, r)
	return
}

func sayHelloRoute(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "hello! my route!!!")

}

func main() {
	myMux := &MyMux{}
	http.ListenAndServe(":8080", myMux)
}

  1. 文件服务器实例
package main

import (
	"log"
	"net/http"
)
/**
    FileServer:
    1.www.xx.com/ 根路径 直接使用

     http.Handle("/", http.FileServer(http.Dir("/tmp")))

  2.www.xx.com/c/ 带有请求路径的 需要添加函数
      http.Handle("/c/", http.StripPrefix("/c/", http.FileServer(http.Dir("/tmp"))))
*/
func main()  {
	err := http.ListenAndServe(":8080", http.FileServer(http.Dir("./")))
	if err != nil {
		log.Fatal(err)
	}

输出:
在这里插入图片描述

  1. handler相关demo
package main

import (
	"io"
	"net/http"
)

func main() {
	mux :=  http.NewServeMux()
	mux.HandleFunc("/baidu", func(w http.ResponseWriter, r *http.Request) {
		http.Redirect(w, r, "http://www.baidu.com", http.StatusOK)
	})

	mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, "hello world")
	})

	mux.HandleFunc("/hehe", sayHehe)

	http.ListenAndServe(":8080", mux)
}

func sayHehe(w http.ResponseWriter, r *http.Request)  {
	io.WriteString(w, "hehe!!!!!")
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:设计师小姐姐 返回首页