package main
import ("fmt";
"strconv";
"os";
"log"
"time"
"net/http"
"io")
const PI = 3.14
type Cal_Area interface{
calArea()
}
type Rectangle struct
{
width float32
len float32
}
func (p Rectangle)calArea(){
fmt.Println("The area of Rectangle is:",(p.width)*(p.len))
}
type Circle struct
{
radius float32
}
func (p Circle)calArea(){
fmt.Println("The area of Circle is:",PI*(p.radius)*(p.radius))
}
func test_interface () {
fmt.Println("Hello world! - go.jsrun.net ")
var cal Cal_Area
cal = Rectangle{width:10.0,len:20.0}
cal.calArea()
cal = Circle{radius:10.0}
cal.calArea()
}
func test_for(){
userMap := make(map[string]string)
user := "user"
for i:=1;i<10;i+=1{
tmpuser := user + strconv.Itoa(i)
userMap[tmpuser]=strconv.Itoa(i)
}
fmt.Println("test for map user2",userMap["user2"])
for usr,pass := range userMap{
fmt.Printf("%s\t %s\n",usr,pass)
}
}
type error interface{
Error() string
}
func readFilePanic(path string){
op,err := os.Open(path)
if err!=nil{
panic(err)
}
fmt.Println("file name:",op.Name())
}
func test_error(path string){
file, err := os.Open(path)
if err != nil{
log.Fatal(err)
}
fmt.Println(file.Name())
}
func worker(count int){
for i:=1;i<count;i++{
time.Sleep(500)
fmt.Print(" ",i)
}
fmt.Println()
}
func test_goroutine(){
now1 := time.Now()
for i:=0;i<3;i++{
worker(10)
}
now2 := time.Now()
fmt.Println("不开协程花费时间:",now2.Sub(now1))
for i:=0;i<3;i++{
go worker(10)
}
now3 := time.Now()
fmt.Println("开协程花费时间:",now3.Sub(now2))
}
func sum_no_chan(s []int,result *int){
*result = 0
for _, v := range s{
*result += v
}
}
func sum_chan(s []int,c chan int){
sum := 0
for _,v := range s{
sum += v
}
c <- sum
}
func test_channel(){
s := []int{1,2,3,4,5,6,7,8}
now1 := time.Now()
sum_1 := 0
sum_no_chan(s,&sum_1)
now2 := time.Now()
fmt.Printf("no channel result:%d \t time: %s",sum_1,now2.Sub(now1))
}
func test_http(){
resp,err := http.Get("http://127.0.0.1")
if err != nil{
log.Fatal(err)
}
body,err := io.ReadAll(resp.Body)
if err != nil{
return
}
fmt.Printf("status %d\n",resp.StatusCode)
fmt.Printf("content %d\n",string(body))
}
func main (){
test_http()
}