Golang之http编程
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编程的更多相关文章
- Golang面向API编程-interface(接口)
Golang面向API编程-interface(接口) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. Golang并不是一种典型的面向对象编程(Object Oriented Pr ...
- golang之面向对象编程
1.Golang语言面向对象编程说明 1)Golang也支持面向对象编程(OOP),但是和传统的面向对象编程有区别,并不是纯粹的面向对象语言.所以我们说Golang支持面向对象编程特性是比较准确的. ...
- [golang note] 网络编程 - RPC编程
net包 • 官方文档 http://godoc.golangtc.com/pkg/net/ Package net provides a portable interface for network ...
- Golang的面向对象编程【结构体、方法、继承、接口】
Golang也支持面向对象编程.但与以前学过传统的面向对象编程语言有区别.1)Golang没有类class,Go语言的结构体struct和类class有相似的特性.2)Golang中不存在继承,方法重 ...
- 关于golang结束了编程风格中对于左大括号要不要换行之争.
golang规定了左大括号必须紧跟在语句后面,这样一下子就结束了各种代码风格之争. 其实golang是继承了早期的C语言,为了节省空间,才将左括号放到代码后面. 哪种编码风格是你的"菜&qu ...
- golang:并发编程总结
并行和并发 并发编程是指在一台处理器上"同时"处理多个任务. 宏观并发:在一段时间内,有多个程序在同时运行. 微观并发:在同一时刻只能有一条指令执行,但多个程序指令被快速的轮换执行 ...
- Golang Linux Shell编程(一)
1.调用系统命令 exec包执行外部命令,它将os.StartProcess进行包装使得它更容易映射到stdin和stdout,并且利用pipe连接i/o func Command(name stri ...
- golang实现tcp编程
实现简单的tcp服务 package main import ( "fmt" "net" ) func main() { fmt.Println("服 ...
- golang中http编程
1. http server package main import ( "fmt" "net/http" ) func main() { // 请求url和对 ...
随机推荐
- 3D Render
记录最近遇到的问题: 1:崩溃问题 由于高频率获取DC异常导致. void D3D11Texture2D::Copy2Window(void* srcdc, uint32_t left, uint32 ...
- 为solr增加用户验证
添加此功能主要是为了增加solr服务器的安全性,不能随便让人访问. 1. 在tomcat的F:\Tomcat 6.0.26_solr\conf\tomcat-users.xml添加用户角色并 ...
- NHibernate.Cfg.HibernateConfigException
在用NHibernate 框架做web 项目时,当项目被成功编译后,按F5 启动调试时,一开始就出现这个错误,刚开始就很郁闷,到底出在哪里?连自己都 不知道,在网上搜来搜去,找了很多的资料终于弄明白了 ...
- cplex-Java-样例代码解析
import ilog.cplex.IloCplex; import ilog.concert.*; /** * * * * 最大化 x1 + 2x2 + 3x3</br> * 约束 &l ...
- uva-10047
我们考虑一个特殊情况,一个独轮车是一个圆环,独轮车靠这个圆环运动,这个圆环上涂有五个不同的颜色,如下图每个颜色段的圆心角是72度,这个圆环在MxN个方格的棋盘上运动,独轮车从棋盘中一个格子的中心点开始 ...
- 写了个TP5下PHP和手机端通信的API接口校验
写了个PHP和手机端通信的API接口校验 直接发函数吧 public function _initialize() { //定义密码和盐 $password="123456"; $ ...
- 35. CentOS-6.3安装拼音输入法
安装方法: su root yum install "@Chinese Support" // 安装中文输入法 exit 装好后,在“系统-->首选项”就会看到有“ ...
- Windows 忘记密码
能进入windows,以前保存的凭据,但是不知道啥. windows下进入cmd net user administrator abc123 这样可以重置密码
- Mysql 获取当天,昨天,本周,本月,上周,上月的起始时间
转自: http://www.cppblog.com/tx7do/archive/2017/07/19/215119.html -- 今天 SELECT DATE_FORMAT(NOW(),'%Y-% ...
- 使用 C++11 编写类似 QT 的信号槽——上篇
了解 QT 的应该知道,QT 有一个信号槽 Singla-Slot 这样的东西.信号槽是 QT 的核心机制,用来替代函数指针,将不相关的对象绑定在一起,实现对象间的通信. 考虑为 Simple2D 添 ...