zoukankan      html  css  js  c++  java
  • golang server示例

    一个简单的web服务器

    package main
    
    import (
    	"fmt"
    	"log"
    	"net/http"
    )
    
    func main() {
    	http.HandleFunc("/", handler)
    	log.Fatal(http.ListenAndServe("localhost:8888", nil))
    }
    
    func handler(w http.ResponseWriter, r *http.Request) {
    	fmt.Println("url.path is ", r.URL.Path)
    }
    

    简单看下Request结构体中几个重要成员

    type Request struct {
        // Form contains the parsed form data, including both the URL
    	// field's query parameters and the POST or PUT form data.
    	// This field is only available after ParseForm is called.
    	// The HTTP client ignores Form and uses Body instead.
    	Form url.Values
    
    	// PostForm contains the parsed form data from POST, PATCH,
    	// or PUT body parameters.
    	//
    	// This field is only available after ParseForm is called.
    	// The HTTP client ignores PostForm and uses Body instead.
    	PostForm url.Values
    
    	// MultipartForm is the parsed multipart form, including file uploads.
    	// This field is only available after ParseMultipartForm is called.
    	// The HTTP client ignores MultipartForm and uses Body instead.
    	MultipartForm *multipart.Form
    }
    

    获取get参数

    func handler(w http.ResponseWriter, r *http.Request) {
    	r.ParseForm()
    	fmt.Println("value of param key is:", r.Form.Get("key"))
    }
    

    获取post参数

    提交方式: application/x-www-form-urlencoded

    func handler(w http.ResponseWriter, r *http.Request) {
    	r.ParseForm()
    	fmt.Println("value of param key is:", r.PostFormValue("key"))
    }
    

    提交方式: json

    type RequestParm struct {
    	Name      string `json:"name"`
    	Age       int    `json:"age"`
    	ScoreList []int  `json:"score_list"`
    }
    // NewDecoder
    func handler(w http.ResponseWriter, r *http.Request) {
    	req := &RequestParm{}
    	err := json.NewDecoder(r.Body).Decode(req)
    	if err != nil {
    		fmt.Println("json decode error")
    		return
    	}
    	fmt.Println(req)
    }
    // Unmarshal
    func handler(w http.ResponseWriter, r *http.Request) {
    	req := &RequestParm{}
    
    	body, err := ioutil.ReadAll(r.Body)
    	if err != nil {
    		panic(err)
    	}
    
    	err = json.Unmarshal(body, req)
    	if err != nil {
    		panic(err)
    	}
    
    	fmt.Println(req)
    }
    

    参考资料

    四种常见的 POST 提交数据方式

  • 相关阅读:
    Vim 配置 winmanager
    删除字符串中重复字符
    检查字符串中是否存在重复字符
    字符串逆序输出
    shell 循环使用
    Windows下JNI执行步骤
    JNI中使用cl命令生成DLL文件
    javaZIP压缩文件
    java Mail发送邮件
    关于在同一个DIV下的Hover效果问题
  • 原文地址:https://www.cnblogs.com/gattaca/p/9462979.html
Copyright © 2011-2022 走看看