Go原生支持http。import("net/http")
Go的http服务性能和nginx比较接近
几行代码就可以实现一个web服务

服务端http

package main

import (
"fmt"
"net/http"
) func Hello(w http.ResponseWriter, r *http.Request) {
fmt.Println("handle hello")
fmt.Fprintf(w, "hello")
}
func Login(w http.ResponseWriter, r *http.Request) {
fmt.Println("handle login")
fmt.Fprintf(w, "login....")
} func main() {
http.HandleFunc("/", Hello)
http.HandleFunc("/user/login", Login)
err := http.ListenAndServe("127.0.0.1:8800", nil)
if err != nil {
fmt.Println("htpp listen failed")
}
}

http客户端

package main

import (
"fmt"
"io/ioutil"
"net/http"
) func main() {
res, err := http.Get("https://www.baidu.com/")
if err != nil {
fmt.Println("get err:", err)
return
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("get data err:", err)
return
}
fmt.Println(string(data))
}

http_head

package main

import (
"fmt"
"net/http"
) var url = []string{
"http://www.baidu.com",
"http://google.com",
"http://taobao.com",
} func main() {
for _, v := range url {
res, err := http.Head(v)
if err != nil {
fmt.Printf("head %s failed,err:%v\n", v, err)
continue
}
fmt.Printf("head succ,status:%v\n", res.Status)
}
}

http_head自定义超时写法

package main

import (
"fmt"
"net"
"net/http"
"time"
) var url = []string{
"http://www.baidu.com",
"http://google.com",
"http://taobao.com",
} func main() {
for _, v := range url {
//超时写法
c := http.Client{
Transport: &http.Transport{
Dial: func(network, addr string) (net.Conn, error) {
timeout := time.Second *
return net.DialTimeout(network, addr, timeout)
},
},
}
resp, err := c.Head(v)
if err != nil {
fmt.Printf("head %s failed,err:%v\n", v, err)
continue
}
fmt.Printf("head succ,status:%v\n", resp.Status)
}
}

http_form写法


package main

import (
"io"
"log"
"net/http"
) const form = `<html><body><form action="#" method="post" name="bar">
<input type="text" name="in"/>
<input type="text" name="in"/>
<input type="submit" value="Submit"/>
</form></body></html>` func SimpleServer(w http.ResponseWriter, request *http.Request) {
io.WriteString(w, "hello,world")
panic("test test")
}
func FormServer(w http.ResponseWriter, request *http.Request) {
w.Header().Set("Content-Type", "text/html")
switch request.Method {
case "GET":
io.WriteString(w, form)
case "POST":
request.ParseForm()
io.WriteString(w, request.Form["in"][1])
io.WriteString(w, "\n")
io.WriteString(w, request.FormValue("in"))
}
} func main() {
//用函数封装了一下
http.HandleFunc("/test1", logPanics(SimpleServer))
http.HandleFunc("/test2", logPanics(FormServer))
if err := http.ListenAndServe(":8088", nil); err != nil {
}
}
//捕获,错误处理
func logPanics(handle http.HandlerFunc) http.HandlerFunc {
return func(write http.ResponseWriter, request *http.Request) {
defer func() {
if x := recover(); x != nil {
log.Printf("[%v]caught panic:%v", request.RemoteAddr, x)
}
}()
handle(write, request) //这里才是
}
}
 

http_template,模板写法

package main

import (
"fmt"
"os"
"text/template"
) type Person struct {
Name string
age string
Title string
} func main() {
t, err := template.ParseFiles("d:/project/src/go_dev/day10/http_form/index.html")
if err != nil {
fmt.Println("parse file err:", err)
return
}
p := Person{Name: "Mary", age: "", Title: "我的个人网站"}
if err := t.Execute(os.Stdout, p); err != nil {
fmt.Println("There was an error:", err.Error())
}
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{.Title}}</title>
</head>
<body>
<p>hello,{{.Name}}</p>
<p>{{.}}</p>
</body>
</html>

用例2:

package main

import (
"fmt"
"html/template"
"io"
"net/http"
) var myTemplate *template.Template type Result struct {
output string
} func (p *Result) Write(b []byte) (n int, err error) {
fmt.Println("called by template")
p.output += string(b)
return len(b), nil
} type Person struct {
Name string
Title string
Age int
} func userInfo(w http.ResponseWriter, r *http.Request) {
fmt.Println("handle hello")
//fmt.Fprintf(w,"hello")
var arr []Person
p := Person{Name: "Mary001", Age: , Title: "我的网站"}
p1 := Person{Name: "Mary002", Age: , Title: "我的个人网站"}
p2 := Person{Name: "Mary003", Age: , Title: "我的网站2"}
arr = append(arr, p)
arr = append(arr, p1)
arr = append(arr, p2) resultWriter := &Result{}
io.WriteString(resultWriter, "hello world")
err := myTemplate.Execute(w, arr)
if err != nil {
fmt.Println(err)
}
fmt.Println("template render data:", resultWriter.output)
//myTemplate.Execute(w, p)
//myTemplate.Execute(os.Stdout, p)
//file, err := os.OpenFile("C:/test.log", os.O_CREATE|os.O_WRONLY, 0755)
//if err != nil {
// fmt.Println("open failed err:", err)
// return
//}
}
func initTemplate(filename string) (err error) {
myTemplate, err = template.ParseFiles(filename)
if err != nil {
fmt.Println("parse file err:", err)
return
}
return
}
func main() {
initTemplate("d:/project/src/go_dev/day10/template_http/index.html")
http.HandleFunc("/user/info", userInfo)
err := http.ListenAndServe("127.0.0.1:8880", nil)
if err != nil {
fmt.Println("http listen failed")
}
}

template.go

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<p>hello world</p>
<table border="">
{{range .}}
<tr>
<td>{{.Name}}</td> <td>{{.Age}}</td><td>{{.Title}}</td>
</tr>
{{end}}
</table>
</body>
</html>

index.html

Golang之http编程的更多相关文章

  1. Golang面向API编程-interface(接口)

    Golang面向API编程-interface(接口) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. Golang并不是一种典型的面向对象编程(Object Oriented Pr ...

  2. golang之面向对象编程

    1.Golang语言面向对象编程说明 1)Golang也支持面向对象编程(OOP),但是和传统的面向对象编程有区别,并不是纯粹的面向对象语言.所以我们说Golang支持面向对象编程特性是比较准确的. ...

  3. [golang note] 网络编程 - RPC编程

    net包 • 官方文档 http://godoc.golangtc.com/pkg/net/ Package net provides a portable interface for network ...

  4. Golang的面向对象编程【结构体、方法、继承、接口】

    Golang也支持面向对象编程.但与以前学过传统的面向对象编程语言有区别.1)Golang没有类class,Go语言的结构体struct和类class有相似的特性.2)Golang中不存在继承,方法重 ...

  5. 关于golang结束了编程风格中对于左大括号要不要换行之争.

    golang规定了左大括号必须紧跟在语句后面,这样一下子就结束了各种代码风格之争. 其实golang是继承了早期的C语言,为了节省空间,才将左括号放到代码后面. 哪种编码风格是你的"菜&qu ...

  6. golang:并发编程总结

    并行和并发 并发编程是指在一台处理器上"同时"处理多个任务. 宏观并发:在一段时间内,有多个程序在同时运行. 微观并发:在同一时刻只能有一条指令执行,但多个程序指令被快速的轮换执行 ...

  7. Golang Linux Shell编程(一)

    1.调用系统命令 exec包执行外部命令,它将os.StartProcess进行包装使得它更容易映射到stdin和stdout,并且利用pipe连接i/o func Command(name stri ...

  8. golang实现tcp编程

    实现简单的tcp服务 package main import ( "fmt" "net" ) func main() { fmt.Println("服 ...

  9. golang中http编程

    1. http server package main import ( "fmt" "net/http" ) func main() { // 请求url和对 ...

随机推荐

  1. elastisSearch-aggregations

    运行结果 统计每个学员的总成绩 这个是索引库使用通配符 优先在本地查询 只在本地节点中查询 只在指定id的节点里面进行查询 查询指定分片的数据 参考代码ESTestAggregation.java p ...

  2. 教Alexa看懂手语,不说话也能控制语音助手

    Alexa.Siri.小度……各种语音助手令人眼花缭乱,但这些设备多是针对能力健全的用户,忽略了听.说能力存在障碍的人群.本文作者敏锐地发现了这一 bug,并训练亚马逊语音助手 Alex 学会识别美式 ...

  3. 使用CMQ和SCF实现邮件发送

    准备腾讯云 API 调用工具 使用 API 命令行工具来管理和运行无服务器云函数(SCF),下面就先来安装配置该工具. 安装 Python 和 PIP Python 环境是腾讯云命令行工具运行时的必要 ...

  4. 异步与websocket

    异步与WebSockets 知识点 理解同步与异步执行过程 理解异步代码的回调写法与yield写法 Tornado异步 异步Web客户端AsyncHTTPClient tornado.web.asyn ...

  5. linux运维工程师工作中的一些常见问题解决方法

    http://blog.sina.com.cn/s/blog_b9fe247a0101anoe.html 1.shell脚本死活不执行 问题:某天研发某同事找我说帮他看看他写的shell脚本,死活不执 ...

  6. python正则表达式re库(自用)

    经典例子: 1.由26个字母组成的字符串 ^[A-Za-z]+$ 2. 中国境内邮政编码 [1-9]\d{5} 3.IP地址 0-99:[1-9]?\d 100-199:1\d{2} 200-249: ...

  7. jssip中文开发文档(完整版)

    jsSip开发文档 (官网地址:http://www.jssip.net/) 完整案例demo下载地址: http://download.csdn.net/download/qq_39421580/1 ...

  8. spring data jpa @query的用法

    @Query注解的用法(Spring Data JPA) 参考文章:http://www.tuicool.com/articles/jQJBNv . 一个使用@Query注解的简单例子 @Query( ...

  9. angular 参考文档

    https://www.w3schools.com/angular/ 参考二: https://www.angular.cn/guide/reactive-forms

  10. leetcode134

    class Solution { public: inline int get_next(int idx, int size) { ? : idx+; } int aux(int idx, vecto ...