├── .gitignore ├── README.md ├── _config.yml ├── cmd ├── Go中的切片-1.md ├── JS中扩展符.md ├── main.go ├── test.md └── url.config ├── controllers ├── category.go ├── label.go ├── md2html.go ├── posts.go ├── removeFile.go └── uploadfile.go ├── database ├── sqlite3.go └── test.db ├── debug ├── front_web ├── .gitignore ├── README.md ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ └── manifest.json ├── src │ ├── App.css │ ├── App.js │ ├── App.test.js │ ├── components │ │ ├── AppBar.js │ │ ├── Article.js │ │ ├── Category.js │ │ ├── Home.js │ │ ├── Label.js │ │ ├── Post.js │ │ └── ShowPosts.js │ ├── index.css │ ├── index.js │ ├── logo.svg │ └── registerServiceWorker.js └── yarn.lock ├── gin.log ├── main.go ├── models ├── category.go ├── label.go ├── post.go ├── post_category.go └── post_label.go ├── posts ├── 0890fb6686475586ea27ca4833af7533.md ├── IMG_2654.jpg ├── b128b7694e4de962e0088bcb1bcb254f.md └── d79e7ba593ca7a422b63047859abf480.md ├── routers └── router.go ├── static ├── IMG_2654.jpg └── photo.png └── vendor └── vendor.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 使用go搭建一个简易的博客系统 2 | 3 | * 后端使用Go语言开发,使用Web框架gin和ORM框架xorm。 4 | * 前端使用React+Metrail-Ui+React-Router4。 5 | * 命令行工具使用`github.com/urfave/cli`开发。 6 | 7 | ## 目前功能 8 | 9 | * 命令行工具能对文章进行上传、删除、和进行请求`Host`进行配置。 10 | * 服务端提供了对于文章的基本增删改查接口,使用`sqlite`数据来存储文章相应的标题、标签和分类等。 11 | * 前端能简单展示文章列表和文章内容,根据标签或者分类展示相关的文章。 12 | 13 | ## 截图 14 | 15 | ![展示图1](http://p9uc2ui6z.bkt.clouddn.com/github/my-blog-by-go/1.png) 16 | 17 | ![展示图2](http://p9uc2ui6z.bkt.clouddn.com/github/my-blog-by-go/2.png) 18 | 19 | ![展示图3](http://p9uc2ui6z.bkt.clouddn.com/github/my-blog-by-go/3.png) 20 | 21 | ## 启动项目 22 | 23 | * 服务端 24 | ```shell 25 | go get -u github.com/zachrey/my-blog-by-go 26 | 27 | cd $GOPATH/src/github.com/zachrey/my-blog-by-go/ 28 | 29 | go run main.go 30 | ``` 31 | 端口默认开启的是本地的`8888`。 32 | 33 | * 前端 34 | ```shell 35 | cd $GOPATH/src/github.com/zachrey/my-blog-by-go/front_web 36 | 37 | yarn && yarn start 38 | ``` 39 | 40 | * 命令行工具 41 | ```shell 42 | cd $GOPATH/src/github.com/zachrey/my-blog-by-go/cmd 43 | 44 | go run main.go --help 45 | ``` 46 | 47 | 这里,前后端和命令行工具都没有进行编译,直接在开发环境中演示。 48 | 49 | 50 | > 如果go 项目中有些依赖包下载不下来,建议翻墙或者去github找相应的库,然后将它clone到你的src/github文件夹相应路劲下。 51 | 52 | ## 项目结构 53 | . 54 | ├── cmd // 命令行工具 55 | ├── controllers // 控制器 56 | ├── database // 数据库连接,配置等 57 | ├── front_web // react前端内容 58 | ├── models // 数据库相关表的操作模板 59 | ├── posts // 存放上传的文章 60 | ├── routers // 路由 61 | ├── static // 静态文件资源,前端打包后就可以打包放到这里面 62 | ├── gin.log // web运行日志 63 | ├── main.go // 程序入口 64 | ├── README.md 65 | └── vendor 66 | 67 | 欢迎讨论和star 68 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-architect -------------------------------------------------------------------------------- /cmd/Go中的切片-1.md: -------------------------------------------------------------------------------- 1 | title: Go中的切片-1 2 | categories: Go, 后端 3 | label: Go, Slice 4 | --------------------------------------------- 5 | 6 | ## 切片的内部实现 7 | 切片是一个很小的对象,对底层数组进行了抽象,并提供相关的操作方法。 8 | 9 | ![](/uploads/post/Go中的切片-1/1.png) 10 | 11 | 12 | 13 | 可以看到切片有三个元数据,一个是指向底层数组头部的指针、一个代表切片的长度、一个代表切片的容量。 14 | 15 | ## 创建切片 16 | ### 使用`make`创建。 17 | ```golang 18 | slice1 := make([]int) // nil 19 | slice2 := make([]int, 5) // {0, 0, 0, 0, 0} 因为int的空值为0 20 | slice3 := make([]int, 5, 10) // {0, 0, 0, 0, 0} 可以增长到10个元素 21 | ``` 22 | 这里看起来`slice2`和`slice3`值的区别不大,但是当谁用`append`方式,容器这个元数据决定,是否新建一个底层数组,下面有具体说的地方。 23 | > **容量小于长度的切片会在编译时报错** 24 | 25 | ### 字面量创建 26 | ```golang 27 | // 创建字符串切片 28 | // 其长度和容量都是 5 个元素 29 | slice := []string{"Red", "Blue", "Green", "Yellow", "Pink"} 30 | // 创建一个整型切片 31 | // 其长度和容量都是 3 个元素 32 | slice := []int{10, 20, 30} 33 | // 创建字符串切片 34 | // 使用空字符串初始化第 100 个元素 35 | slice := []string{99: ""} 36 | ``` 37 | 38 | **如果在创建的时候`[]`写了值,例如`[6]`,这样创建的是数组,而不是切片** 39 | 40 | ## nil 和空切片 41 | 因为切片也是属于指针的,所以它的空值就是`nil` 42 | ```golang 43 | var slice []int 44 | // slice == nil 45 | 46 | var slice1 = []int{} 47 | // slice1 != nil 48 | len(slice1) == 0 // true 49 | ``` 50 | 51 | ## 使用切片创建切片 52 | 53 | ```golang 54 | // 创建一个整型切片 55 | // 其长度和容量都是 5 个元素 56 | slice := []int{10, 20, 30, 40, 50} 57 | // 创建一个新切片 58 | // 其长度为 2 个元素,容量为 4 个元素 59 | newSlice := slice[1:3] 60 | ``` 61 | 执行完代码清单 4-25 中的切片动作后,我们有了两个切片,它们**共享同一段底层数组**,但通过不同的切片会看到底层数组的不同部分(见图 4-12)。 62 | ![](/uploads/post/Go中的切片-1/2.png) 63 | 64 | ## 使用 append 向切片增加元素 65 | ```golang 66 | // 创建一个整型切片 67 | // 其长度和容量都是 5 个元素 68 | slice := []int{10, 20, 30, 40, 50} 69 | // 创建一个新切片 70 | // 其长度为 2 个元素,容量为 4 个元素 71 | newSlice := slice[1:3] 72 | // 使用原有的容量来分配一个新元素 73 | // 将新元素赋值为 60 74 | newSlice = append(newSlice, 60) 75 | ``` 76 | 结果如下 77 | ![](/uploads/post/Go中的切片-1/3.png) 78 | 79 | **注意的地方** 80 | 函数 append 会智能地处理底层数组的容量增长。在切片的容量小于 1000 个元素时,总是会成倍地增加容量。一旦元素个数超过 1000,容量的增长因子会设为1.25,也就是会每次增加 25%的容量。随着语言的演化,这种增长算法可能会有所改变。 81 | 82 | 看如下代码 83 | ```golang 84 | slice := []int{1, 2, 3, 4} 85 | newSlice := append(slice, 5, 6) // 增加两个,因为原来slice的容器只有4,但是这里增加了2个,容量不够了,所以就自动的产生了新的底层数组,新的切片的容量变成了8。 86 | newSlice2 := append(newSlice, 6) // 这里在newSlice的基础上增加一个元素,但是没有超过newSlice的容量8,所以不会产生新的底层数组,newSlice2和newSlice使用同一个底层数组。 87 | 88 | newSlice2[0] = 10 // 观察前两个切片的值 89 | fmt.Println(newSlice2[0]) // 10 90 | fmt.Println(slice[0]) // 1 91 | fmt.Println(newSlice[0]) // 10 92 | ``` 93 | 94 | ## 函数传递 95 | 在函数间传递数组的时候,是复制的数组的值,如果数组过多,就会消耗过多内存,所以数组一般会使用`func(arr *[]int)`指针的形式传递。但是切片区别于数组,它只是一个**指向数组的指针**,所以就算底层数组很大,在函数传递的时候,只会**复制切片**(指针),不会复制底层数组,所以传输效率很高。 96 | 97 | 98 | > 文中部分代码和图片来着[《Go语言实战》](https://book.douban.com/subject/27015617/) 99 | > 100 | > 感谢作者 -------------------------------------------------------------------------------- /cmd/JS中扩展符.md: -------------------------------------------------------------------------------- 1 | title: JS中扩展符(spread/rest)的各种表现 2 | categories: javascript 3 | label: JS, ES6 4 | --------------------------------------------- 5 | 6 | 7 |
8 | 每一天都以许下希望开始,以收获经验结束。 9 |
10 | 11 | # 深入 '...' 各种情况下的表现形式 12 | 在js中,合并多个对象是一种很常见的操作,在ES5的时候,没有一种很方便的语法来进行对象的合并。在ES6中引入了一个对象函数Object.assgin(source, [target]),再之后又引入了**对象的spread语法**。 13 | 14 | 15 | 16 | 如下: 17 | ```javascript 18 | const cat = { 19 | legs: 4, 20 | sound: 'meow', 21 | }; 22 | const dog = { 23 | ...cat, 24 | sound: 'woof' 25 | }; 26 | 27 | /* 最后结果 28 | dog => { 29 | legs: 4, 30 | sound: 'woof', 31 | } 32 | */ 33 | ``` 34 | 35 | ## spread与属性的可枚举配置 36 | 在ES5及之后的规范中,对象的每一个属性都存在几个来描述该属性的属性。这些值用来描述对象的属性是否可写、可枚举和可配置的状态。这里只说可枚举属性,可枚举属性是一个bool值,代表对象属性是否可以被访问。我们可以使用`Object.keys()`来访问**自己的和可枚举属性**,也可以使用`for...in`语句来**遍历所有可枚举的属性** 37 | 如下: 38 | ```javascript 39 | const person = { 40 | name: 'zachrey', 41 | age: 21, 42 | }; 43 | Object.keys(person); // ['name', 'age'] 44 | console.log({...person}); 45 | /* 46 | { 47 | name: 'zachrey', 48 | age: 21, 49 | } 50 | */ 51 | ``` 52 | 所以`name` `age`是`person`对象中的可枚举属性,目前来说spread可以克隆所有的可枚举属性。 53 | 现在我们来给`person`定义一个不可以枚举的属性,再使用spread看能不能克隆出来。 54 | ```javascript 55 | Object.defineProperty(person, 'sex', { 56 | enumerable: false, 57 | value: 'male', 58 | }); 59 | console.log(person['sex']);// male 60 | 61 | const clonePerson = { 62 | ...person, 63 | }; 64 | console.log(Object.keys(person));// ['name', 'age'] 65 | console.log(clonePerson); 66 | /* 67 | { 68 | name: 'zachrey', 69 | age: 21, 70 | } 71 | */ 72 | ``` 73 | 通过以上可以看出来: 74 | 1. 不可枚举属性,可以被访问,使用`console.log`打印出来。 75 | 2. `...`**并不能克隆**不可枚举属性。 76 | 3. `...`的表现形式与`Object.keys`的表现形式相同。 77 | 78 | ## spread与自身属性 79 | 对于一个js对象,它的属性可以是自己的也可能是原型链上的,接下来简单的实现以下继承。 80 | ```javascript 81 | const personB = Object.create(person, { 82 | profession: { 83 | value: 'development', 84 | enumerable: true, 85 | } 86 | }); 87 | console.log(personB.hasOwnProperty('profession')); // => true 88 | console.log(personB.hasOwnProperty('name')); // => false 89 | console.log(personB.hasOwnProperty('age')); // => false 90 | ``` 91 | 如上,只有`profession`是属于`personB`自身的。 92 | **Object spread从自己的源属性中进行复制的时候,会忽略继承的属性。** 93 | 如下: 94 | ```javascript 95 | const cloneB = { ...personB }; 96 | console.log(cloneB); // => { profession: 'development' } 97 | ``` 98 | > Object spread可以从源对象中复制自己的和可枚举的属性。和Object.keys()相同。 99 | 100 | ## Object spread规则:最后属性获胜 101 | *** 后者扩展属性覆盖具有相同键的早期属性 *** 102 | 如下: 103 | ```javascript 104 | const cat = { 105 | sound: 'meow', 106 | legs: 4, 107 | }; 108 | 109 | const dog = { 110 | ...cat, 111 | ...{ 112 | sound: 'woof' // <----- 覆盖 cat.sound 113 | } 114 | }; 115 | console.log(dog); // => { sound: 'woof', legs: 4 } 116 | 117 | const anotherDog = { 118 | ...cat, 119 | sound: 'woof' // <---- Overwrites cat.sound 120 | }; 121 | console.log(anotherDog); // => { sound: 'woof', legs: 4 } 122 | ``` 123 | ## 浅拷贝 124 | spread对值是复合类型的属性,只会拷贝它对该值得应用。 125 | 如下: 126 | ```javascript 127 | 128 | const laptop = { 129 | name: 'MacBook Pro', 130 | screen: { size: 17, isRetina: true } 131 | }; 132 | const laptopClone = { ...laptop }; 133 | console.log(laptop === laptopClone); // => false 134 | console.log(laptop.screen === laptopClone.screen); // => true 135 | ``` 136 | 首先比较`laptop === laptopClone`,其值是false。主对象被正确克隆。 137 | 138 | 然而,`laptop.screen === laptopClone.screen`值是true。这意味着,`laptop.screen`和`laptopClone.screen`引用相同的嵌套对象,但没有复制。 139 | 140 | ## 原型丢失 141 | 142 | 这里先声明一个类: 143 | ```javascript 144 | class Game { 145 | constructor(name) { 146 | this.name = name; 147 | } 148 | getMessage() { 149 | return `I like ${this.name}!`; 150 | } 151 | } 152 | const doom = new Game('Doom'); 153 | console.log(doom instanceof Game); // => true console.log(doom.name); // => "Doom" 154 | console.log(doom.getMessage()); // => "I like Doom!" 155 | ``` 156 | 接下来我们使用spread克隆调用构造函数创建的`doom`实例: 157 | ```javascript 158 | const doomClone = { ...doom }; 159 | console.log(doomClone instanceof Game); // => false 160 | console.log(doomClone.name); // => "Doom" 161 | console.log(doomClone.getMessage()); // => TypeError: doomClone.getMessage is not a function 162 | ``` 163 | `...doom`只将自己的属性name复制到`doomClone`而已。doomClone是一个普通的JavaScript对象,其原型是`Object.prototype`,而不是`Game.prototype`,这是可以预期的。Object Spread**不保存源对象的原型**。 164 | 想要修复原型可以使用`Object.setPrototypeOf(doomClone, Game.prototype)`。 165 | 使用Object.assign()可以更合理的克隆doom: 166 | ```javascript 167 | const doomFullClone = Object.assign(new Game(), doom); 168 | console.log(doomFullClone instanceof Game); // => true 169 | console.log(doomFullClone.name); // => "Doom" 170 | console.log(doomFullClone.getMessage()); // => "I like Doom!" 171 | ``` 172 | 173 | ## 传播undefined、null和基本类型 174 | ```javascript 175 | const nothing = undefined; 176 | const missingObject = null; 177 | const two = 2; 178 | console.log({ ...nothing }); // => { } 179 | console.log({ ...missingObject }); // => { } 180 | console.log({ ...two }); // => { } 181 | ``` 182 | 183 | ## 总结 184 | 185 | Object spread有一些规则要记住: 186 | 187 | * 它从源对象中提取自己的和可枚举的属性 188 | * 扩展的属性具有相同键的,后者会覆盖前者 189 | 190 | 与此同时,Object spread是简短而且富有表现力的,同时在嵌套对象上也能很好的工作,同时也保持更新的不变性。它可以轻松的实现对象克隆、合并和填充默认属性。 191 | 192 | 在结构性赋值中使用Object rest语法,可以收集剩余的属性。 193 | 194 | 实际上,Object rest和Object spread是JavaScript的重要补充。 195 | 196 | >[原文链接](https://www.w3cplus.com/javascript/how-three-dots-changed-javascript-object-rest-spread-properties.html "原文链接") 197 | 198 | !['干巴爹'](/uploads/ganbadie.jpg) -------------------------------------------------------------------------------- /cmd/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "log" 10 | "mime/multipart" 11 | "net/http" 12 | "os" 13 | "path/filepath" 14 | 15 | "github.com/urfave/cli" 16 | ) 17 | 18 | func main() { 19 | app := cli.NewApp() 20 | app.Name = "bpost" 21 | app.Usage = "Managing blog posts" 22 | app.Version = "0.0.1" 23 | 24 | var filePath string 25 | var fileName string 26 | var host string 27 | 28 | app.Flags = []cli.Flag{ 29 | cli.StringFlag{ 30 | Name: "upload,up", 31 | Usage: "Upload an article by that `file path`", 32 | Destination: &filePath, 33 | }, 34 | cli.StringFlag{ 35 | Name: "remove,rm", 36 | Usage: "Remove the article by that `file name`", 37 | Destination: &fileName, 38 | }, 39 | cli.StringFlag{ 40 | Name: "config,cf", 41 | Usage: "Config http request `host`", 42 | Destination: &host, 43 | }, 44 | } 45 | var url = "http://localhost:8888" 46 | isexists := exists("./url.config") 47 | if isexists { 48 | file, rdRrr := ioutil.ReadFile("./url.config") 49 | if rdRrr != nil { 50 | log.Fatalln("[ERROR] ", rdRrr) 51 | } 52 | url = string(file) 53 | } 54 | 55 | app.Action = func(c *cli.Context) error { 56 | if filePath != "" { 57 | upload(filePath, url) 58 | } 59 | if fileName != "" { 60 | remove(fileName, url) 61 | } 62 | if host != "" { 63 | config(host) 64 | } 65 | return nil 66 | } 67 | err := app.Run(os.Args) 68 | checkErr(err) 69 | } 70 | 71 | func upload(filePath, url string) { 72 | _, err := os.Stat(filePath) //os.Stat获取文件信息 73 | if err != nil { 74 | if os.IsExist(err) == false { 75 | log.Fatalf("%s 路径不存在", filePath) 76 | } 77 | } 78 | // 创建表单文件 79 | // CreateFormFile 用来创建表单,第一个参数是字段名,第二个参数是文件名 80 | buf := new(bytes.Buffer) 81 | writer := multipart.NewWriter(buf) 82 | fileName := filepath.Base(filePath) 83 | formFile, err := writer.CreateFormFile("upload", fileName) 84 | if err != nil { 85 | log.Fatalf("Create form file failed: %s\n", err) 86 | } 87 | 88 | // 从文件读取数据,写入表单 89 | srcFile, err := os.Open(filePath) 90 | if err != nil { 91 | log.Fatalf("Open source file failed: %s\n", err) 92 | } 93 | defer srcFile.Close() 94 | _, err = io.Copy(formFile, srcFile) 95 | if err != nil { 96 | log.Fatalf("Write to form file falied: %s\n", err) 97 | } 98 | 99 | // 发送表单 100 | contentType := writer.FormDataContentType() 101 | writer.Close() // 发送之前必须调用Close()以写入结尾行 102 | var res *http.Response 103 | res, err = http.Post(url+"/upload", contentType, buf) 104 | if err != nil { 105 | log.Fatalf("Post failed: %s\n", err) 106 | } 107 | defer res.Body.Close() 108 | body, _ := ioutil.ReadAll(res.Body) 109 | var dataMap map[string]interface{} 110 | json.Unmarshal(body, &dataMap) 111 | if dataMap["status"] != 0 { 112 | log.Fatalf("Post failed: %s\n", dataMap["msg"]) 113 | } 114 | log.Println("[SUCCESS] Upload file is successfully. ", filePath) 115 | } 116 | 117 | func remove(fileName, url string) { 118 | res, err := http.Get(url + "/remove?name=" + fileName) 119 | if err != nil { 120 | log.Fatalf("Remove failed: %s\n", err) 121 | } 122 | defer res.Body.Close() 123 | body, _ := ioutil.ReadAll(res.Body) 124 | var dataMap map[string]interface{} 125 | json.Unmarshal(body, &dataMap) 126 | if dataMap["status"] != 0 { 127 | log.Fatalf("Post failed: %s\n", dataMap["msg"]) 128 | } 129 | fmt.Println("[SUCCESS] Remove file is successfully. ", fileName) 130 | } 131 | 132 | func config(host string) { 133 | var file *os.File 134 | var err error 135 | file, err = os.OpenFile("./url.config", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm) 136 | defer file.Close() 137 | 138 | if err != nil { 139 | log.Fatalln("[ERROR] ", err) 140 | } 141 | 142 | _, err = file.WriteString(host) 143 | if err != nil { 144 | log.Fatalln("[ERROR] ", err) 145 | } else { 146 | log.Fatalln("[SUCCESSFUL] 配置成功!") 147 | } 148 | } 149 | 150 | func checkErr(e error) { 151 | if e != nil { 152 | log.Fatalln("ERROR:", e) 153 | } 154 | } 155 | 156 | func exists(path string) bool { 157 | _, err := os.Stat(path) //os.Stat获取文件信息 158 | if err != nil { 159 | if os.IsExist(err) { 160 | return true 161 | } 162 | return false 163 | } 164 | return true 165 | } 166 | -------------------------------------------------------------------------------- /cmd/test.md: -------------------------------------------------------------------------------- 1 | title: 一个博客的名称 2 | categories: 分类1, 分类2, 分类3 3 | label: 标签1, 标签2 4 | --------------------------------------------- 5 | 6 | # 标题 7 | **it's golang** 8 | -------------------------------------------------------------------------------- /cmd/url.config: -------------------------------------------------------------------------------- 1 | http://localhost:8888 -------------------------------------------------------------------------------- /controllers/category.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/gin-gonic/gin" 7 | "github.com/zachrey/blog/models" 8 | ) 9 | 10 | //GetLabels 获取所有的标签 11 | func GetCategoies(c *gin.Context) { 12 | labels := models.GetCategories() 13 | c.JSON(http.StatusOK, gin.H{ 14 | "status": 0, 15 | "data": labels, 16 | }) 17 | } 18 | -------------------------------------------------------------------------------- /controllers/label.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/gin-gonic/gin" 7 | "github.com/zachrey/blog/models" 8 | ) 9 | 10 | //GetLabels 获取所有的标签 11 | func GetLabels(c *gin.Context) { 12 | labels := models.GetLabels() 13 | c.JSON(http.StatusOK, gin.H{ 14 | "status": 0, 15 | "data": labels, 16 | }) 17 | } 18 | -------------------------------------------------------------------------------- /controllers/md2html.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "io/ioutil" 5 | "log" 6 | "net/http" 7 | "strconv" 8 | "strings" 9 | 10 | "github.com/gin-gonic/gin" 11 | "github.com/russross/blackfriday" 12 | "github.com/zachrey/blog/models" 13 | ) 14 | 15 | // GetHtmlStr 根据params获取id,读取本地md文件,然后返回字符串 16 | func GetHtmlStr(c *gin.Context) { 17 | postid := c.Param("postid") 18 | if postid == "" { 19 | c.JSON(http.StatusNotFound, gin.H{ 20 | "status": 1, 21 | "msg": "postid 不能为空", 22 | }) 23 | } 24 | postID, err := strconv.ParseInt(postid, 10, 64) 25 | if err != nil { 26 | log.Println(err) 27 | c.JSON(http.StatusNotFound, gin.H{ 28 | "status": 1, 29 | "msg": "postid can't convert to int64, the error information: " + err.Error(), 30 | }) 31 | } 32 | 33 | postInfo := models.GetPostByID(postID) 34 | file, openErr := ioutil.ReadFile("./posts/" + postInfo.FileName) 35 | if openErr != nil { 36 | log.Println(err) 37 | c.JSON(http.StatusNotFound, gin.H{ 38 | "status": 1, 39 | "msg": err.Error(), 40 | }) 41 | } 42 | 43 | lines := strings.Split(string(file), "\n") 44 | body := strings.Join(lines[5:], "\n") 45 | body = string(blackfriday.MarkdownCommon([]byte(body))) 46 | c.JSON(http.StatusOK, gin.H{ 47 | "status": 0, 48 | "data": body, 49 | }) 50 | } 51 | -------------------------------------------------------------------------------- /controllers/posts.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "strconv" 7 | 8 | "github.com/gin-gonic/gin" 9 | "github.com/zachrey/blog/models" 10 | ) 11 | 12 | //GetPosts 获取所有的文章 13 | func GetPosts(c *gin.Context) { 14 | labels := models.GetPosts() 15 | c.JSON(http.StatusOK, gin.H{ 16 | "status": 0, 17 | "data": labels, 18 | }) 19 | } 20 | 21 | //GetPostByLabelId 根据label id获取post 22 | func GetPostByLabelId(c *gin.Context) { 23 | labelid := c.Param("labelid") 24 | if labelid == "" { 25 | c.JSON(http.StatusNotFound, gin.H{ 26 | "status": 1, 27 | "msg": "labelid 不能为空", 28 | }) 29 | } 30 | labelId, err := strconv.ParseInt(labelid, 10, 64) 31 | posts := models.GetPostsByPLId(labelId) 32 | if err != nil { 33 | log.Println(err) 34 | c.JSON(http.StatusNotFound, gin.H{ 35 | "status": 1, 36 | "msg": "labelid can't convert to int64, the error information: " + err.Error(), 37 | }) 38 | } 39 | c.JSON(http.StatusOK, gin.H{ 40 | "status": 0, 41 | "data": posts, 42 | }) 43 | } 44 | 45 | //GetPostByCategoryId category id获取post 46 | func GetPostByCategoryId(c *gin.Context) { 47 | categoryid := c.Param("categoryid") 48 | if categoryid == "" { 49 | c.JSON(http.StatusNotFound, gin.H{ 50 | "status": 1, 51 | "msg": "categoryid 不能为空", 52 | }) 53 | } 54 | categoryId, err := strconv.ParseInt(categoryid, 10, 64) 55 | posts := models.GetPostsByPCId(categoryId) 56 | if err != nil { 57 | log.Println(err) 58 | c.JSON(http.StatusNotFound, gin.H{ 59 | "status": 1, 60 | "msg": "categoryid can't convert to int64, the error information: " + err.Error(), 61 | }) 62 | } 63 | c.JSON(http.StatusOK, gin.H{ 64 | "status": 0, 65 | "data": posts, 66 | }) 67 | } 68 | -------------------------------------------------------------------------------- /controllers/removeFile.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | "os" 7 | "sync" 8 | 9 | "github.com/gin-gonic/gin" 10 | "github.com/zachrey/blog/models" 11 | ) 12 | 13 | var wg sync.WaitGroup 14 | 15 | // RemoveFile 根据标题删除文章及相关项 16 | func RemoveFile(c *gin.Context) { 17 | wg.Add(3) 18 | fileName := c.Query("name") 19 | if fileName == "" { 20 | c.JSON(http.StatusOK, gin.H{ 21 | "status": 1, 22 | "msg": "Filed name is empty.", 23 | }) 24 | return 25 | } 26 | 27 | post := models.GetPostByTitle(fileName) 28 | 29 | // 删除分类关联表 30 | go func() { 31 | models.RemovePCByPostID(post.Id) 32 | wg.Done() 33 | }() 34 | // 删除标签关联表 35 | go func() { 36 | models.RemovePLByPostID(post.Id) 37 | wg.Done() 38 | }() 39 | // 删除文件 40 | go func() { 41 | err := os.Remove("./posts/" + post.FileName) 42 | if err != nil { 43 | log.Println("[ERROR] ", err) 44 | } 45 | wg.Done() 46 | }() 47 | wg.Wait() 48 | models.RemovePostByID(post.Id) 49 | 50 | c.JSON(http.StatusOK, gin.H{ 51 | "status": 0, 52 | "msg": "删除文章成功!", 53 | }) 54 | } 55 | -------------------------------------------------------------------------------- /controllers/uploadfile.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "crypto/md5" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "io/ioutil" 9 | "log" 10 | "math" 11 | "net/http" 12 | "os" 13 | "path/filepath" 14 | "regexp" 15 | "strings" 16 | "sync" 17 | "unicode" 18 | 19 | "github.com/gin-gonic/gin" 20 | "github.com/zachrey/blog/models" 21 | ) 22 | 23 | const postDir = "./posts/" 24 | 25 | var gr sync.WaitGroup 26 | var isShouldRemove = false 27 | 28 | // UpLoadFile 上传文件的控制器 29 | func UpLoadFile(c *gin.Context) { 30 | file, header, err := c.Request.FormFile("upload") 31 | filename := header.Filename 32 | md5FileName := fmt.Sprintf("%x", md5.Sum([]byte(filename))) 33 | fileExt := filepath.Ext(postDir + filename) 34 | filePath := postDir + md5FileName + fileExt 35 | log.Println("[INFO] upload file: ", header.Filename) 36 | 37 | has := hasSameNameFile(md5FileName+fileExt, postDir) 38 | if has { 39 | c.JSON(http.StatusOK, gin.H{ 40 | "status": 1, 41 | "msg": "服务器已有相同文件名称", 42 | }) 43 | return 44 | } 45 | 46 | // 根据文件名的md5值,创建服务器上的文件 47 | out, err := os.Create(filePath) 48 | if err != nil { 49 | log.Fatal(err) 50 | } 51 | 52 | // 处理完整个上传过程后,是否需要删除创建的文件,在存在错误的情况下 53 | defer func() { 54 | if isShouldRemove { 55 | err = os.Remove(filePath) 56 | if err != nil { 57 | log.Println("[ERROR] ", err) 58 | } 59 | } 60 | }() 61 | defer out.Close() 62 | 63 | _, err = io.Copy(out, file) 64 | if err != nil { 65 | log.Fatal(err) 66 | } 67 | 68 | err = readMdFileInfo(filePath) 69 | if err != nil { 70 | isShouldRemove = true 71 | c.JSON(http.StatusOK, gin.H{ 72 | "status": 1, 73 | "msg": err.Error(), 74 | }) 75 | return 76 | } 77 | 78 | c.JSON(http.StatusOK, gin.H{ 79 | "status": 0, 80 | "msg": "上传成功", 81 | }) 82 | } 83 | 84 | func readMdFileInfo(filePath string) error { 85 | fileread, _ := ioutil.ReadFile(filePath) 86 | lines := strings.Split(string(fileread), "\n") 87 | body := strings.Join(lines[5:], "") 88 | textAmount := GetStrLength(body) 89 | log.Println(lines) 90 | const ( 91 | TITLE = "title: " 92 | CATEGORIES = "categories: " 93 | LABEL = "label: " 94 | ) 95 | var ( 96 | postId int64 97 | postCh chan int64 98 | categoryCh chan []int64 99 | labelCh chan []int64 100 | ) 101 | mdInfo := make(map[string]string) 102 | 103 | for i, lens := 0, len(lines); i < lens && i < 5; i++ { // 只查找前五行 104 | switch { 105 | case strings.HasPrefix(lines[i], TITLE): 106 | mdInfo[TITLE] = strings.TrimLeft(lines[i], TITLE) 107 | postCh = make(chan int64) 108 | go models.InsertPost(mdInfo[TITLE], filepath.Base(filePath), int64(textAmount), postCh) 109 | case strings.HasPrefix(lines[i], CATEGORIES): 110 | mdInfo[CATEGORIES] = strings.TrimLeft(lines[i], CATEGORIES) 111 | categoryCh = make(chan []int64) 112 | go models.InsertCategory(mdInfo[CATEGORIES], categoryCh) 113 | case strings.HasPrefix(lines[i], LABEL): 114 | mdInfo[LABEL] = strings.TrimLeft(lines[i], LABEL) 115 | labelCh = make(chan []int64) 116 | go models.InsertLabel(mdInfo[LABEL], labelCh) 117 | } 118 | } 119 | postId = <-postCh 120 | if postId == 0 { 121 | return errors.New("服务器上已有相同文章标题") 122 | } 123 | log.Println("[INFO] postId: ", postId) 124 | if categoryCh != nil { 125 | go func() { 126 | categoryIds := <-categoryCh 127 | log.Println("[INFO] categoryIds: ", categoryIds) 128 | 129 | for _, v := range categoryIds { 130 | models.InsertPostAndCategory(postId, v) 131 | } 132 | }() 133 | } 134 | 135 | if labelCh != nil { 136 | go func() { 137 | labels := <-labelCh 138 | log.Println("[INFO] labels: ", labels) 139 | 140 | for _, v := range labels { 141 | models.InsertPostAndLabel(postId, v) 142 | } 143 | }() 144 | } 145 | return nil 146 | // 接下来就是将各种信息存入数据库 147 | } 148 | 149 | func hasSameNameFile(fileName, dir string) bool { 150 | files, _ := ioutil.ReadDir(dir) 151 | for _, f := range files { 152 | if fileName == f.Name() { 153 | return true 154 | } 155 | } 156 | return false 157 | } 158 | 159 | // GetStrLength 返回输入的字符串的字数,汉字和中文标点算 1 个字数,英文和其他字符 2 个算 1 个字数,不足 1 个算 1个 160 | func GetStrLength(str string) float64 { 161 | var total float64 162 | 163 | reg := regexp.MustCompile("/·|,|。|《|》|‘|’|”|“|;|:|【|】|?|(|)|、/") 164 | 165 | for _, r := range str { 166 | if unicode.Is(unicode.Scripts["Han"], r) || reg.Match([]byte(string(r))) { 167 | total = total + 1 168 | } else { 169 | total = total + 0.5 170 | } 171 | } 172 | 173 | return math.Ceil(total) 174 | } 175 | -------------------------------------------------------------------------------- /database/sqlite3.go: -------------------------------------------------------------------------------- 1 | package database 2 | 3 | import ( 4 | "log" 5 | 6 | "github.com/xormplus/xorm" 7 | ) 8 | 9 | // ORM xorm引擎的实例 10 | var ORM *xorm.Engine 11 | 12 | func init() { 13 | var err error 14 | ORM, err = xorm.NewEngine("sqlite3", "./database/test.db") 15 | if err != nil { 16 | log.Fatalln(err) 17 | return 18 | } 19 | err = ORM.Ping() 20 | if err != nil { 21 | log.Fatalln(err) 22 | return 23 | } 24 | ORM.ShowSQL(true) 25 | } 26 | -------------------------------------------------------------------------------- /database/test.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce-16/my-blog-by-go/38d3e5491d079394a9ce066127c917fe8010ba74/database/test.db -------------------------------------------------------------------------------- /debug: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce-16/my-blog-by-go/38d3e5491d079394a9ce066127c917fe8010ba74/debug -------------------------------------------------------------------------------- /front_web/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /front_web/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). 2 | 3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). 5 | 6 | ## Table of Contents 7 | 8 | - [Updating to New Releases](#updating-to-new-releases) 9 | - [Sending Feedback](#sending-feedback) 10 | - [Folder Structure](#folder-structure) 11 | - [Available Scripts](#available-scripts) 12 | - [npm start](#npm-start) 13 | - [npm test](#npm-test) 14 | - [npm run build](#npm-run-build) 15 | - [npm run eject](#npm-run-eject) 16 | - [Supported Browsers](#supported-browsers) 17 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) 18 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 19 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 20 | - [Debugging in the Editor](#debugging-in-the-editor) 21 | - [Formatting Code Automatically](#formatting-code-automatically) 22 | - [Changing the Page ``](#changing-the-page-title) 23 | - [Installing a Dependency](#installing-a-dependency) 24 | - [Importing a Component](#importing-a-component) 25 | - [Code Splitting](#code-splitting) 26 | - [Adding a Stylesheet](#adding-a-stylesheet) 27 | - [Post-Processing CSS](#post-processing-css) 28 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) 29 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) 30 | - [Using the `public` Folder](#using-the-public-folder) 31 | - [Changing the HTML](#changing-the-html) 32 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 33 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 34 | - [Using Global Variables](#using-global-variables) 35 | - [Adding Bootstrap](#adding-bootstrap) 36 | - [Using a Custom Theme](#using-a-custom-theme) 37 | - [Adding Flow](#adding-flow) 38 | - [Adding a Router](#adding-a-router) 39 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 40 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 41 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 42 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 43 | - [Can I Use Decorators?](#can-i-use-decorators) 44 | - [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests) 45 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 46 | - [Node](#node) 47 | - [Ruby on Rails](#ruby-on-rails) 48 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 49 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) 50 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually) 51 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy) 52 | - [Using HTTPS in Development](#using-https-in-development) 53 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 54 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 55 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 56 | - [Running Tests](#running-tests) 57 | - [Filename Conventions](#filename-conventions) 58 | - [Command Line Interface](#command-line-interface) 59 | - [Version Control Integration](#version-control-integration) 60 | - [Writing Tests](#writing-tests) 61 | - [Testing Components](#testing-components) 62 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 63 | - [Initializing Test Environment](#initializing-test-environment) 64 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 65 | - [Coverage Reporting](#coverage-reporting) 66 | - [Continuous Integration](#continuous-integration) 67 | - [Disabling jsdom](#disabling-jsdom) 68 | - [Snapshot Testing](#snapshot-testing) 69 | - [Editor Integration](#editor-integration) 70 | - [Debugging Tests](#debugging-tests) 71 | - [Debugging Tests in Chrome](#debugging-tests-in-chrome) 72 | - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code) 73 | - [Developing Components in Isolation](#developing-components-in-isolation) 74 | - [Getting Started with Storybook](#getting-started-with-storybook) 75 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist) 76 | - [Publishing Components to npm](#publishing-components-to-npm) 77 | - [Making a Progressive Web App](#making-a-progressive-web-app) 78 | - [Opting Out of Caching](#opting-out-of-caching) 79 | - [Offline-First Considerations](#offline-first-considerations) 80 | - [Progressive Web App Metadata](#progressive-web-app-metadata) 81 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size) 82 | - [Deployment](#deployment) 83 | - [Static Server](#static-server) 84 | - [Other Solutions](#other-solutions) 85 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 86 | - [Building for Relative Paths](#building-for-relative-paths) 87 | - [Azure](#azure) 88 | - [Firebase](#firebase) 89 | - [GitHub Pages](#github-pages) 90 | - [Heroku](#heroku) 91 | - [Netlify](#netlify) 92 | - [Now](#now) 93 | - [S3 and CloudFront](#s3-and-cloudfront) 94 | - [Surge](#surge) 95 | - [Advanced Configuration](#advanced-configuration) 96 | - [Troubleshooting](#troubleshooting) 97 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 98 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 99 | - [`npm run build` exits too early](#npm-run-build-exits-too-early) 100 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 101 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) 102 | - [Moment.js locales are missing](#momentjs-locales-are-missing) 103 | - [Alternatives to Ejecting](#alternatives-to-ejecting) 104 | - [Something Missing?](#something-missing) 105 | 106 | ## Updating to New Releases 107 | 108 | Create React App is divided into two packages: 109 | 110 | * `create-react-app` is a global command-line utility that you use to create new projects. 111 | * `react-scripts` is a development dependency in the generated projects (including this one). 112 | 113 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 114 | 115 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. 116 | 117 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. 118 | 119 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. 120 | 121 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 122 | 123 | ## Sending Feedback 124 | 125 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 126 | 127 | ## Folder Structure 128 | 129 | After creation, your project should look like this: 130 | 131 | ``` 132 | my-app/ 133 | README.md 134 | node_modules/ 135 | package.json 136 | public/ 137 | index.html 138 | favicon.ico 139 | src/ 140 | App.css 141 | App.js 142 | App.test.js 143 | index.css 144 | index.js 145 | logo.svg 146 | ``` 147 | 148 | For the project to build, **these files must exist with exact filenames**: 149 | 150 | * `public/index.html` is the page template; 151 | * `src/index.js` is the JavaScript entry point. 152 | 153 | You can delete or rename the other files. 154 | 155 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 156 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. 157 | 158 | Only files inside `public` can be used from `public/index.html`.<br> 159 | Read instructions below for using assets from JavaScript and HTML. 160 | 161 | You can, however, create more top-level directories.<br> 162 | They will not be included in the production build so you can use them for things like documentation. 163 | 164 | ## Available Scripts 165 | 166 | In the project directory, you can run: 167 | 168 | ### `npm start` 169 | 170 | Runs the app in the development mode.<br> 171 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 172 | 173 | The page will reload if you make edits.<br> 174 | You will also see any lint errors in the console. 175 | 176 | ### `npm test` 177 | 178 | Launches the test runner in the interactive watch mode.<br> 179 | See the section about [running tests](#running-tests) for more information. 180 | 181 | ### `npm run build` 182 | 183 | Builds the app for production to the `build` folder.<br> 184 | It correctly bundles React in production mode and optimizes the build for the best performance. 185 | 186 | The build is minified and the filenames include the hashes.<br> 187 | Your app is ready to be deployed! 188 | 189 | See the section about [deployment](#deployment) for more information. 190 | 191 | ### `npm run eject` 192 | 193 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 194 | 195 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 196 | 197 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 198 | 199 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 200 | 201 | ## Supported Browsers 202 | 203 | By default, the generated project uses the latest version of React. 204 | 205 | You can refer [to the React documentation](https://reactjs.org/docs/react-dom.html#browser-support) for more information about supported browsers. 206 | 207 | ## Supported Language Features and Polyfills 208 | 209 | This project supports a superset of the latest JavaScript standard.<br> 210 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 211 | 212 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 213 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 214 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). 215 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) 216 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal). 217 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. 218 | 219 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 220 | 221 | While we recommend using experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. 222 | 223 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: 224 | 225 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). 226 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). 227 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). 228 | 229 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. 230 | 231 | Also note that using some newer syntax features like `for...of` or `[...nonArrayValue]` causes Babel to emit code that depends on ES6 runtime features and might not work without a polyfill. When in doubt, use [Babel REPL](https://babeljs.io/repl/) to see what any specific syntax compiles down to. 232 | 233 | ## Syntax Highlighting in the Editor 234 | 235 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. 236 | 237 | ## Displaying Lint Output in the Editor 238 | 239 | >Note: this feature is available with `react-scripts@0.2.0` and higher.<br> 240 | >It also only works with npm 3 or higher. 241 | 242 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 243 | 244 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. 245 | 246 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: 247 | 248 | ```js 249 | { 250 | "extends": "react-app" 251 | } 252 | ``` 253 | 254 | Now your editor should report the linting warnings. 255 | 256 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes. 257 | 258 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. 259 | 260 | ## Debugging in the Editor 261 | 262 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** 263 | 264 | Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. 265 | 266 | ### Visual Studio Code 267 | 268 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. 269 | 270 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 271 | 272 | ```json 273 | { 274 | "version": "0.2.0", 275 | "configurations": [{ 276 | "name": "Chrome", 277 | "type": "chrome", 278 | "request": "launch", 279 | "url": "http://localhost:3000", 280 | "webRoot": "${workspaceRoot}/src", 281 | "sourceMapPathOverrides": { 282 | "webpack:///src/*": "${webRoot}/*" 283 | } 284 | }] 285 | } 286 | ``` 287 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 288 | 289 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. 290 | 291 | Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting). 292 | 293 | ### WebStorm 294 | 295 | You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed. 296 | 297 | In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration. 298 | 299 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 300 | 301 | Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm. 302 | 303 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. 304 | 305 | ## Formatting Code Automatically 306 | 307 | Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/). 308 | 309 | To format our code whenever we make a commit in git, we need to install the following dependencies: 310 | 311 | ```sh 312 | npm install --save husky lint-staged prettier 313 | ``` 314 | 315 | Alternatively you may use `yarn`: 316 | 317 | ```sh 318 | yarn add husky lint-staged prettier 319 | ``` 320 | 321 | * `husky` makes it easy to use githooks as if they are npm scripts. 322 | * `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8). 323 | * `prettier` is the JavaScript formatter we will run before commits. 324 | 325 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. 326 | 327 | Add the following line to `scripts` section: 328 | 329 | ```diff 330 | "scripts": { 331 | + "precommit": "lint-staged", 332 | "start": "react-scripts start", 333 | "build": "react-scripts build", 334 | ``` 335 | 336 | Next we add a 'lint-staged' field to the `package.json`, for example: 337 | 338 | ```diff 339 | "dependencies": { 340 | // ... 341 | }, 342 | + "lint-staged": { 343 | + "src/**/*.{js,jsx,json,css}": [ 344 | + "prettier --single-quote --write", 345 | + "git add" 346 | + ] 347 | + }, 348 | "scripts": { 349 | ``` 350 | 351 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx,json,css}"` to format your entire project for the first time. 352 | 353 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page. 354 | 355 | ## Changing the Page `<title>` 356 | 357 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 358 | 359 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. 360 | 361 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. 362 | 363 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). 364 | 365 | ## Installing a Dependency 366 | 367 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: 368 | 369 | ```sh 370 | npm install --save react-router 371 | ``` 372 | 373 | Alternatively you may use `yarn`: 374 | 375 | ```sh 376 | yarn add react-router 377 | ``` 378 | 379 | This works for any library, not just `react-router`. 380 | 381 | ## Importing a Component 382 | 383 | This project setup supports ES6 modules thanks to Babel.<br> 384 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. 385 | 386 | For example: 387 | 388 | ### `Button.js` 389 | 390 | ```js 391 | import React, { Component } from 'react'; 392 | 393 | class Button extends Component { 394 | render() { 395 | // ... 396 | } 397 | } 398 | 399 | export default Button; // Don’t forget to use export default! 400 | ``` 401 | 402 | ### `DangerButton.js` 403 | 404 | 405 | ```js 406 | import React, { Component } from 'react'; 407 | import Button from './Button'; // Import a component from another file 408 | 409 | class DangerButton extends Component { 410 | render() { 411 | return <Button color="red" />; 412 | } 413 | } 414 | 415 | export default DangerButton; 416 | ``` 417 | 418 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. 419 | 420 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. 421 | 422 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. 423 | 424 | Learn more about ES6 modules: 425 | 426 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) 427 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 428 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 429 | 430 | ## Code Splitting 431 | 432 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand. 433 | 434 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module. 435 | 436 | Here is an example: 437 | 438 | ### `moduleA.js` 439 | 440 | ```js 441 | const moduleA = 'Hello'; 442 | 443 | export { moduleA }; 444 | ``` 445 | ### `App.js` 446 | 447 | ```js 448 | import React, { Component } from 'react'; 449 | 450 | class App extends Component { 451 | handleClick = () => { 452 | import('./moduleA') 453 | .then(({ moduleA }) => { 454 | // Use moduleA 455 | }) 456 | .catch(err => { 457 | // Handle failure 458 | }); 459 | }; 460 | 461 | render() { 462 | return ( 463 | <div> 464 | <button onClick={this.handleClick}>Load</button> 465 | </div> 466 | ); 467 | } 468 | } 469 | 470 | export default App; 471 | ``` 472 | 473 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. 474 | 475 | You can also use it with `async` / `await` syntax if you prefer it. 476 | 477 | ### With React Router 478 | 479 | If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app). 480 | 481 | Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation. 482 | 483 | ## Adding a Stylesheet 484 | 485 | This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: 486 | 487 | ### `Button.css` 488 | 489 | ```css 490 | .Button { 491 | padding: 20px; 492 | } 493 | ``` 494 | 495 | ### `Button.js` 496 | 497 | ```js 498 | import React, { Component } from 'react'; 499 | import './Button.css'; // Tell Webpack that Button.js uses these styles 500 | 501 | class Button extends Component { 502 | render() { 503 | // You can use them as regular CSS styles 504 | return <div className="Button" />; 505 | } 506 | } 507 | ``` 508 | 509 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. 510 | 511 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. 512 | 513 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. 514 | 515 | ## Post-Processing CSS 516 | 517 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. 518 | 519 | For example, this: 520 | 521 | ```css 522 | .App { 523 | display: flex; 524 | flex-direction: row; 525 | align-items: center; 526 | } 527 | ``` 528 | 529 | becomes this: 530 | 531 | ```css 532 | .App { 533 | display: -webkit-box; 534 | display: -ms-flexbox; 535 | display: flex; 536 | -webkit-box-orient: horizontal; 537 | -webkit-box-direction: normal; 538 | -ms-flex-direction: row; 539 | flex-direction: row; 540 | -webkit-box-align: center; 541 | -ms-flex-align: center; 542 | align-items: center; 543 | } 544 | ``` 545 | 546 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). 547 | 548 | ## Adding a CSS Preprocessor (Sass, Less etc.) 549 | 550 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). 551 | 552 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. 553 | 554 | First, let’s install the command-line interface for Sass: 555 | 556 | ```sh 557 | npm install --save node-sass-chokidar 558 | ``` 559 | 560 | Alternatively you may use `yarn`: 561 | 562 | ```sh 563 | yarn add node-sass-chokidar 564 | ``` 565 | 566 | Then in `package.json`, add the following lines to `scripts`: 567 | 568 | ```diff 569 | "scripts": { 570 | + "build-css": "node-sass-chokidar src/ -o src/", 571 | + "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 572 | "start": "react-scripts start", 573 | "build": "react-scripts build", 574 | "test": "react-scripts test --env=jsdom", 575 | ``` 576 | 577 | >Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. 578 | 579 | Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. 580 | 581 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. 582 | 583 | To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`. 584 | 585 | ``` 586 | "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/", 587 | "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive", 588 | ``` 589 | 590 | This will allow you to do imports like 591 | 592 | ```scss 593 | @import 'styles/_colors.scss'; // assuming a styles directory under src/ 594 | @import 'nprogress/nprogress'; // importing a css file from the nprogress node module 595 | ``` 596 | 597 | At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. 598 | 599 | As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: 600 | 601 | ```sh 602 | npm install --save npm-run-all 603 | ``` 604 | 605 | Alternatively you may use `yarn`: 606 | 607 | ```sh 608 | yarn add npm-run-all 609 | ``` 610 | 611 | Then we can change `start` and `build` scripts to include the CSS preprocessor commands: 612 | 613 | ```diff 614 | "scripts": { 615 | "build-css": "node-sass-chokidar src/ -o src/", 616 | "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 617 | - "start": "react-scripts start", 618 | - "build": "react-scripts build", 619 | + "start-js": "react-scripts start", 620 | + "start": "npm-run-all -p watch-css start-js", 621 | + "build-js": "react-scripts build", 622 | + "build": "npm-run-all build-css build-js", 623 | "test": "react-scripts test --env=jsdom", 624 | "eject": "react-scripts eject" 625 | } 626 | ``` 627 | 628 | Now running `npm start` and `npm run build` also builds Sass files. 629 | 630 | **Why `node-sass-chokidar`?** 631 | 632 | `node-sass` has been reported as having the following issues: 633 | 634 | - `node-sass --watch` has been reported to have *performance issues* in certain conditions when used in a virtual machine or with docker. 635 | 636 | - Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939) 637 | 638 | - `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891) 639 | 640 | `node-sass-chokidar` is used here as it addresses these issues. 641 | 642 | ## Adding Images, Fonts, and Files 643 | 644 | With Webpack, using static assets like images and fonts works similarly to CSS. 645 | 646 | You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. 647 | 648 | To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebookincubator/create-react-app/issues/1153). 649 | 650 | Here is an example: 651 | 652 | ```js 653 | import React from 'react'; 654 | import logo from './logo.png'; // Tell Webpack this JS file uses this image 655 | 656 | console.log(logo); // /logo.84287d09.png 657 | 658 | function Header() { 659 | // Import result is the URL of your image 660 | return <img src={logo} alt="Logo" />; 661 | } 662 | 663 | export default Header; 664 | ``` 665 | 666 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 667 | 668 | This works in CSS too: 669 | 670 | ```css 671 | .Logo { 672 | background-image: url(./logo.png); 673 | } 674 | ``` 675 | 676 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. 677 | 678 | Please be advised that this is also a custom feature of Webpack. 679 | 680 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 681 | An alternative way of handling static assets is described in the next section. 682 | 683 | ## Using the `public` Folder 684 | 685 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 686 | 687 | ### Changing the HTML 688 | 689 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 690 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 691 | 692 | ### Adding Assets Outside of the Module System 693 | 694 | You can also add other assets to the `public` folder. 695 | 696 | Note that we normally encourage you to `import` assets in JavaScript files instead. 697 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). 698 | This mechanism provides a number of benefits: 699 | 700 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 701 | * Missing files cause compilation errors instead of 404 errors for your users. 702 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 703 | 704 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 705 | 706 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 707 | 708 | Inside `index.html`, you can use it like this: 709 | 710 | ```html 711 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 712 | ``` 713 | 714 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 715 | 716 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 717 | 718 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 719 | 720 | ```js 721 | render() { 722 | // Note: this is an escape hatch and should be used sparingly! 723 | // Normally we recommend using `import` for getting asset URLs 724 | // as described in “Adding Images and Fonts” above this section. 725 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 726 | } 727 | ``` 728 | 729 | Keep in mind the downsides of this approach: 730 | 731 | * None of the files in `public` folder get post-processed or minified. 732 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 733 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 734 | 735 | ### When to Use the `public` Folder 736 | 737 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. 738 | The `public` folder is useful as a workaround for a number of less common cases: 739 | 740 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 741 | * You have thousands of images and need to dynamically reference their paths. 742 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 743 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 744 | 745 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 746 | 747 | ## Using Global Variables 748 | 749 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 750 | 751 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 752 | 753 | ```js 754 | const $ = window.$; 755 | ``` 756 | 757 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 758 | 759 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 760 | 761 | ## Adding Bootstrap 762 | 763 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 764 | 765 | Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 766 | 767 | ```sh 768 | npm install --save react-bootstrap bootstrap@3 769 | ``` 770 | 771 | Alternatively you may use `yarn`: 772 | 773 | ```sh 774 | yarn add react-bootstrap bootstrap@3 775 | ``` 776 | 777 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: 778 | 779 | ```js 780 | import 'bootstrap/dist/css/bootstrap.css'; 781 | import 'bootstrap/dist/css/bootstrap-theme.css'; 782 | // Put any other imports below so that CSS from your 783 | // components takes precedence over default styles. 784 | ``` 785 | 786 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 787 | 788 | ```js 789 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 790 | ``` 791 | 792 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 793 | 794 | ### Using a Custom Theme 795 | 796 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 797 | We suggest the following approach: 798 | 799 | * Create a new package that depends on the package you wish to customize, e.g. Bootstrap. 800 | * Add the necessary build steps to tweak the theme, and publish your package on npm. 801 | * Install your own theme npm package as a dependency of your app. 802 | 803 | Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. 804 | 805 | ## Adding Flow 806 | 807 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 808 | 809 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 810 | 811 | To add Flow to a Create React App project, follow these steps: 812 | 813 | 1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). 814 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 815 | 3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. 816 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 817 | 818 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 819 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 820 | In the future we plan to integrate it into Create React App even more closely. 821 | 822 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 823 | 824 | ## Adding a Router 825 | 826 | Create React App doesn't prescribe a specific routing solution, but [React Router](https://reacttraining.com/react-router/) is the most popular one. 827 | 828 | To add it, run: 829 | 830 | ```sh 831 | npm install --save react-router-dom 832 | ``` 833 | 834 | Alternatively you may use `yarn`: 835 | 836 | ```sh 837 | yarn add react-router-dom 838 | ``` 839 | 840 | To try it, delete all the code in `src/App.js` and replace it with any of the examples on its website. The [Basic Example](https://reacttraining.com/react-router/web/example/basic) is a good place to get started. 841 | 842 | Note that [you may need to configure your production server to support client-side routing](#serving-apps-with-client-side-routing) before deploying your app. 843 | 844 | ## Adding Custom Environment Variables 845 | 846 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 847 | 848 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 849 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 850 | `REACT_APP_`. 851 | 852 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 853 | 854 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 855 | 856 | These environment variables will be defined for you on `process.env`. For example, having an environment 857 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 858 | 859 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 860 | 861 | These environment variables can be useful for displaying information conditionally based on where the project is 862 | deployed or consuming sensitive data that lives outside of version control. 863 | 864 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 865 | in the environment inside a `<form>`: 866 | 867 | ```jsx 868 | render() { 869 | return ( 870 | <div> 871 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 872 | <form> 873 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 874 | </form> 875 | </div> 876 | ); 877 | } 878 | ``` 879 | 880 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 881 | 882 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 883 | 884 | ```html 885 | <div> 886 | <small>You are running this application in <b>development</b> mode.</small> 887 | <form> 888 | <input type="hidden" value="abcdef" /> 889 | </form> 890 | </div> 891 | ``` 892 | 893 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 894 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 895 | a `.env` file. Both of these ways are described in the next few sections. 896 | 897 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 898 | 899 | ```js 900 | if (process.env.NODE_ENV !== 'production') { 901 | analytics.disable(); 902 | } 903 | ``` 904 | 905 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 906 | 907 | ### Referencing Environment Variables in the HTML 908 | 909 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 910 | 911 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 912 | 913 | ```html 914 | <title>%REACT_APP_WEBSITE_NAME% 915 | ``` 916 | 917 | Note that the caveats from the above section apply: 918 | 919 | * Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 920 | * The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 921 | 922 | ### Adding Temporary Environment Variables In Your Shell 923 | 924 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 925 | life of the shell session. 926 | 927 | #### Windows (cmd.exe) 928 | 929 | ```cmd 930 | set "REACT_APP_SECRET_CODE=abcdef" && npm start 931 | ``` 932 | 933 | (Note: Quotes around the variable assignment are required to avoid a trailing whitespace.) 934 | 935 | #### Windows (Powershell) 936 | 937 | ```Powershell 938 | ($env:REACT_APP_SECRET_CODE = "abcdef") -and (npm start) 939 | ``` 940 | 941 | #### Linux, macOS (Bash) 942 | 943 | ```bash 944 | REACT_APP_SECRET_CODE=abcdef npm start 945 | ``` 946 | 947 | ### Adding Development Environment Variables In `.env` 948 | 949 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 950 | 951 | To define permanent environment variables, create a file called `.env` in the root of your project: 952 | 953 | ``` 954 | REACT_APP_SECRET_CODE=abcdef 955 | ``` 956 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid [accidentally exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 957 | 958 | `.env` files **should be** checked into source control (with the exclusion of `.env*.local`). 959 | 960 | #### What other `.env` files can be used? 961 | 962 | >Note: this feature is **available with `react-scripts@1.0.0` and higher**. 963 | 964 | * `.env`: Default. 965 | * `.env.local`: Local overrides. **This file is loaded for all environments except test.** 966 | * `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. 967 | * `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. 968 | 969 | Files on the left have more priority than files on the right: 970 | 971 | * `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` 972 | * `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` 973 | * `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) 974 | 975 | These variables will act as the defaults if the machine does not explicitly set them.
976 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 977 | 978 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 979 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 980 | 981 | #### Expanding Environment Variables In `.env` 982 | 983 | >Note: this feature is available with `react-scripts@1.1.0` and higher. 984 | 985 | Expand variables already on your machine for use in your `.env` file (using [dotenv-expand](https://github.com/motdotla/dotenv-expand)). 986 | 987 | For example, to get the environment variable `npm_package_version`: 988 | 989 | ``` 990 | REACT_APP_VERSION=$npm_package_version 991 | # also works: 992 | # REACT_APP_VERSION=${npm_package_version} 993 | ``` 994 | 995 | Or expand variables local to the current `.env` file: 996 | 997 | ``` 998 | DOMAIN=www.example.com 999 | REACT_APP_FOO=$DOMAIN/foo 1000 | REACT_APP_BAR=$DOMAIN/bar 1001 | ``` 1002 | 1003 | ## Can I Use Decorators? 1004 | 1005 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
1006 | Create React App doesn’t support decorator syntax at the moment because: 1007 | 1008 | * It is an experimental proposal and is subject to change. 1009 | * The current specification version is not officially supported by Babel. 1010 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 1011 | 1012 | However in many cases you can rewrite decorator-based code without decorators just as fine.
1013 | Please refer to these two threads for reference: 1014 | 1015 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 1016 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 1017 | 1018 | Create React App will add decorator support when the specification advances to a stable stage. 1019 | 1020 | ## Fetching Data with AJAX Requests 1021 | 1022 | React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like [axios](https://github.com/axios/axios) or the [`fetch()` API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provided by the browser. Conveniently, Create React App includes a polyfill for `fetch()` so you can use it without worrying about the browser support. 1023 | 1024 | The global `fetch` function allows to easily makes AJAX requests. It takes in a URL as an input and returns a `Promise` that resolves to a `Response` object. You can find more information about `fetch` [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch). 1025 | 1026 | This project also includes a [Promise polyfill](https://github.com/then/promise) which provides a full implementation of Promises/A+. A Promise represents the eventual result of an asynchronous operation, you can find more information about Promises [here](https://www.promisejs.org/) and [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). Both axios and `fetch()` use Promises under the hood. You can also use the [`async / await`](https://davidwalsh.name/async-await) syntax to reduce the callback nesting. 1027 | 1028 | You can learn more about making AJAX requests from React components in [the FAQ entry on the React website](https://reactjs.org/docs/faq-ajax.html). 1029 | 1030 | ## Integrating with an API Backend 1031 | 1032 | These tutorials will help you to integrate your app with an API backend running on another port, 1033 | using `fetch()` to access it. 1034 | 1035 | ### Node 1036 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 1037 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 1038 | 1039 | ### Ruby on Rails 1040 | 1041 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 1042 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 1043 | 1044 | ## Proxying API Requests in Development 1045 | 1046 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 1047 | 1048 | People often serve the front-end React app from the same host and port as their backend implementation.
1049 | For example, a production setup might look like this after the app is deployed: 1050 | 1051 | ``` 1052 | / - static server returns index.html with React app 1053 | /todos - static server returns index.html with React app 1054 | /api/todos - server handles any /api/* requests using the backend implementation 1055 | ``` 1056 | 1057 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 1058 | 1059 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 1060 | 1061 | ```js 1062 | "proxy": "http://localhost:4000", 1063 | ``` 1064 | 1065 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will **only** attempt to send requests without `text/html` in its `Accept` header to the proxy. 1066 | 1067 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 1068 | 1069 | ``` 1070 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 1071 | ``` 1072 | 1073 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 1074 | 1075 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
1076 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 1077 | 1078 | * [Configure the proxy yourself](#configuring-the-proxy-manually) 1079 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 1080 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 1081 | 1082 | ### "Invalid Host Header" Errors After Configuring Proxy 1083 | 1084 | When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). 1085 | 1086 | This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebookincubator/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: 1087 | 1088 | >Invalid Host header 1089 | 1090 | To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: 1091 | 1092 | ``` 1093 | HOST=mypublicdevhost.com 1094 | ``` 1095 | 1096 | If you restart the development server now and load the app from the specified host, it should work. 1097 | 1098 | If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** 1099 | 1100 | ``` 1101 | # NOTE: THIS IS DANGEROUS! 1102 | # It exposes your machine to attacks from the websites you visit. 1103 | DANGEROUSLY_DISABLE_HOST_CHECK=true 1104 | ``` 1105 | 1106 | We don’t recommend this approach. 1107 | 1108 | ### Configuring the Proxy Manually 1109 | 1110 | >Note: this feature is available with `react-scripts@1.0.0` and higher. 1111 | 1112 | If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).
1113 | You may also specify any configuration value [`http-proxy-middleware`](https://github.com/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://github.com/nodejitsu/node-http-proxy#options) supports. 1114 | ```js 1115 | { 1116 | // ... 1117 | "proxy": { 1118 | "/api": { 1119 | "target": "", 1120 | "ws": true 1121 | // ... 1122 | } 1123 | } 1124 | // ... 1125 | } 1126 | ``` 1127 | 1128 | All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. 1129 | 1130 | If you need to specify multiple proxies, you may do so by specifying additional entries. 1131 | Matches are regular expressions, so that you can use a regexp to match multiple paths. 1132 | ```js 1133 | { 1134 | // ... 1135 | "proxy": { 1136 | // Matches any request starting with /api 1137 | "/api": { 1138 | "target": "", 1139 | "ws": true 1140 | // ... 1141 | }, 1142 | // Matches any request starting with /foo 1143 | "/foo": { 1144 | "target": "", 1145 | "ssl": true, 1146 | "pathRewrite": { 1147 | "^/foo": "/foo/beta" 1148 | } 1149 | // ... 1150 | }, 1151 | // Matches /bar/abc.html but not /bar/sub/def.html 1152 | "/bar/[^/]*[.]html": { 1153 | "target": "", 1154 | // ... 1155 | }, 1156 | // Matches /baz/abc.html and /baz/sub/def.html 1157 | "/baz/.*/.*[.]html": { 1158 | "target": "" 1159 | // ... 1160 | } 1161 | } 1162 | // ... 1163 | } 1164 | ``` 1165 | 1166 | ### Configuring a WebSocket Proxy 1167 | 1168 | When setting up a WebSocket proxy, there are a some extra considerations to be aware of. 1169 | 1170 | If you’re using a WebSocket engine like [Socket.io](https://socket.io/), you must have a Socket.io server running that you can use as the proxy target. Socket.io will not work with a standard WebSocket server. Specifically, don't expect Socket.io to work with [the websocket.org echo test](http://websocket.org/echo.html). 1171 | 1172 | There’s some good documentation available for [setting up a Socket.io server](https://socket.io/docs/). 1173 | 1174 | Standard WebSockets **will** work with a standard WebSocket server as well as the websocket.org echo test. You can use libraries like [ws](https://github.com/websockets/ws) for the server, with [native WebSockets in the browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). 1175 | 1176 | Either way, you can proxy WebSocket requests manually in `package.json`: 1177 | 1178 | ```js 1179 | { 1180 | // ... 1181 | "proxy": { 1182 | "/socket": { 1183 | // Your compatible WebSocket server 1184 | "target": "ws://", 1185 | // Tell http-proxy-middleware that this is a WebSocket proxy. 1186 | // Also allows you to proxy WebSocket requests without an additional HTTP request 1187 | // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade 1188 | "ws": true 1189 | // ... 1190 | } 1191 | } 1192 | // ... 1193 | } 1194 | ``` 1195 | 1196 | ## Using HTTPS in Development 1197 | 1198 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 1199 | 1200 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 1201 | 1202 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 1203 | 1204 | #### Windows (cmd.exe) 1205 | 1206 | ```cmd 1207 | set HTTPS=true&&npm start 1208 | ``` 1209 | 1210 | #### Windows (Powershell) 1211 | 1212 | ```Powershell 1213 | ($env:HTTPS = $true) -and (npm start) 1214 | ``` 1215 | 1216 | (Note: the lack of whitespace is intentional.) 1217 | 1218 | #### Linux, macOS (Bash) 1219 | 1220 | ```bash 1221 | HTTPS=true npm start 1222 | ``` 1223 | 1224 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 1225 | 1226 | ## Generating Dynamic `` Tags on the Server 1227 | 1228 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 1229 | 1230 | ```html 1231 | 1232 | 1233 | 1234 | 1235 | 1236 | ``` 1237 | 1238 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! 1239 | 1240 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 1241 | 1242 | ## Pre-Rendering into Static HTML Files 1243 | 1244 | If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) or [react-snap](https://github.com/stereobooster/react-snap) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. 1245 | 1246 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 1247 | 1248 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 1249 | 1250 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 1251 | 1252 | ## Injecting Data from the Server into the Page 1253 | 1254 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 1255 | 1256 | ```js 1257 | 1258 | 1259 | 1260 | 1263 | ``` 1264 | 1265 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** 1266 | 1267 | ## Running Tests 1268 | 1269 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
1270 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 1271 | 1272 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. 1273 | 1274 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. 1275 | 1276 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. 1277 | 1278 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. 1279 | 1280 | ### Filename Conventions 1281 | 1282 | Jest will look for test files with any of the following popular naming conventions: 1283 | 1284 | * Files with `.js` suffix in `__tests__` folders. 1285 | * Files with `.test.js` suffix. 1286 | * Files with `.spec.js` suffix. 1287 | 1288 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 1289 | 1290 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. 1291 | 1292 | ### Command Line Interface 1293 | 1294 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. 1295 | 1296 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: 1297 | 1298 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 1299 | 1300 | ### Version Control Integration 1301 | 1302 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. 1303 | 1304 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. 1305 | 1306 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. 1307 | 1308 | ### Writing Tests 1309 | 1310 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. 1311 | 1312 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 1313 | 1314 | ```js 1315 | import sum from './sum'; 1316 | 1317 | it('sums numbers', () => { 1318 | expect(sum(1, 2)).toEqual(3); 1319 | expect(sum(2, 2)).toEqual(4); 1320 | }); 1321 | ``` 1322 | 1323 | All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).
1324 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](https://facebook.github.io/jest/docs/en/expect.html#tohavebeencalled) to create “spies” or mock functions. 1325 | 1326 | ### Testing Components 1327 | 1328 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. 1329 | 1330 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: 1331 | 1332 | ```js 1333 | import React from 'react'; 1334 | import ReactDOM from 'react-dom'; 1335 | import App from './App'; 1336 | 1337 | it('renders without crashing', () => { 1338 | const div = document.createElement('div'); 1339 | ReactDOM.render(, div); 1340 | }); 1341 | ``` 1342 | 1343 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot of value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. 1344 | 1345 | When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. 1346 | 1347 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run: 1348 | 1349 | ```sh 1350 | npm install --save enzyme enzyme-adapter-react-16 react-test-renderer 1351 | ``` 1352 | 1353 | Alternatively you may use `yarn`: 1354 | 1355 | ```sh 1356 | yarn add enzyme enzyme-adapter-react-16 react-test-renderer 1357 | ``` 1358 | 1359 | As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. (The examples above use the adapter for React 16.) 1360 | 1361 | The adapter will also need to be configured in your [global setup file](#initializing-test-environment): 1362 | 1363 | #### `src/setupTests.js` 1364 | ```js 1365 | import { configure } from 'enzyme'; 1366 | import Adapter from 'enzyme-adapter-react-16'; 1367 | 1368 | configure({ adapter: new Adapter() }); 1369 | ``` 1370 | 1371 | >Note: Keep in mind that if you decide to "eject" before creating `src/setupTests.js`, the resulting `package.json` file won't contain any reference to it. [Read here](#initializing-test-environment) to learn how to add this after ejecting. 1372 | 1373 | Now you can write a smoke test with it: 1374 | 1375 | ```js 1376 | import React from 'react'; 1377 | import { shallow } from 'enzyme'; 1378 | import App from './App'; 1379 | 1380 | it('renders without crashing', () => { 1381 | shallow(); 1382 | }); 1383 | ``` 1384 | 1385 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `, 18 | 19 | ] 20 | render() { 21 | return ( 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 |
30 |
31 | ); 32 | } 33 | } 34 | 35 | export default App; 36 | -------------------------------------------------------------------------------- /front_web/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /front_web/src/components/AppBar.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { withStyles } from '@material-ui/core/styles'; 4 | import AppBar from '@material-ui/core/AppBar'; 5 | import Toolbar from '@material-ui/core/Toolbar'; 6 | import Typography from '@material-ui/core/Typography'; 7 | import {withRouter} from "react-router-dom"; 8 | 9 | const styles = { 10 | root: { 11 | flexGrow: 1, 12 | }, 13 | flex: { 14 | flex: 1, 15 | }, 16 | menuButton: { 17 | marginLeft: -12, 18 | marginRight: 20, 19 | }, 20 | }; 21 | 22 | function ButtonAppBar(props) { 23 | const { classes, rightButton, history } = props; 24 | 25 | const handleClick = () => { 26 | history.push("/") 27 | } 28 | 29 | return ( 30 |
31 | 32 | 33 | 34 | Zachrey's blog 35 | 36 | {rightButton} 37 | 38 | 39 |
40 | ); 41 | } 42 | 43 | ButtonAppBar.propTypes = { 44 | classes: PropTypes.object.isRequired, 45 | rightButton: PropTypes.arrayOf(PropTypes.element) 46 | }; 47 | 48 | export default withRouter(withStyles(styles)(ButtonAppBar)); -------------------------------------------------------------------------------- /front_web/src/components/Article.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { withStyles } from '@material-ui/core/styles'; 4 | import Paper from '@material-ui/core/Paper'; 5 | import Typography from '@material-ui/core/Typography'; 6 | import withRouter from 'react-router-dom/withRouter'; 7 | 8 | const styles = theme => ({ 9 | root: theme.mixins.gutters({ 10 | paddingTop: 16, 11 | paddingBottom: 16, 12 | marginTop: theme.spacing.unit * 3, 13 | }), 14 | }); 15 | 16 | class PaperSheet extends Component { 17 | constructor(props) { 18 | super(props); 19 | this.state = { 20 | html: "", 21 | } 22 | } 23 | componentDidMount = async () => { 24 | const { location } = this.props; 25 | const data = await fetch("/get-html-str/" + location.state.id) 26 | const json = await data.json() 27 | if (json.status === 0) { 28 | this.setState({ 29 | html: json.data, 30 | }) 31 | } 32 | } 33 | render() { 34 | const { classes } = this.props; 35 | return ( 36 |
37 | 38 |
41 |
42 |
43 |
44 | ); 45 | } 46 | } 47 | 48 | export default withRouter(withStyles(styles)(PaperSheet)); -------------------------------------------------------------------------------- /front_web/src/components/Category.js: -------------------------------------------------------------------------------- 1 | import React, {Component} from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import {withStyles} from '@material-ui/core/styles'; 4 | import Chip from '@material-ui/core/Chip'; 5 | 6 | 7 | import ShowPosts from './ShowPosts' 8 | import Post from './Post' 9 | 10 | 11 | const styles = theme => ({ 12 | root: { 13 | display: 'flex', 14 | justifyContent: 'center', 15 | flexWrap: 'wrap', 16 | margin: '8% 5%' 17 | }, 18 | chip: { 19 | margin: theme.spacing.unit 20 | } 21 | }); 22 | 23 | 24 | class Chips extends Component { 25 | 26 | constructor(props) { 27 | super(props) 28 | this.state = { 29 | chips: [], 30 | tips: "点击分类查看相应文章", 31 | posts: [], 32 | isShow: false, 33 | disable: true, 34 | } 35 | } 36 | 37 | componentDidMount = () => { 38 | fetch('/get-categoies') 39 | .then(data => data.json()) 40 | .then(json => { 41 | if (json.status === 0) { 42 | this.renderChip(json.data) 43 | } 44 | }) 45 | .catch(err => console.err("ERROR: ", err)) 46 | } 47 | 48 | handleClick = (id, label) => { 49 | fetch('/get-posts-by-category/' + id) 50 | .then(data => data.json()) 51 | .then(json => { 52 | if (json.status === 0) { 53 | this.setState({ 54 | posts: json.data.map(item => ( 55 | 62 | )), 63 | tips: label, 64 | isShow: true, 65 | disable: false, 66 | }) 67 | } 68 | }) 69 | .catch(err => console.err("ERROR: ", err)) 70 | } 71 | 72 | renderChip = (data) => { 73 | if (Array.isArray(data)) { 74 | this.setState({ 75 | chips: data.map(item => ( 76 | { 82 | this.handleClick(item.Id, item.Category) 83 | }} 84 | /> 85 | )) 86 | }) 87 | } 88 | } 89 | 90 | render() { 91 | const {classes} = this.props; 92 | return ( 93 |
94 |
{this.state.chips}
95 | 96 | { this.state.posts} 97 | 98 |
99 | ); 100 | } 101 | } 102 | 103 | Chips.propTypes = { 104 | classes: PropTypes.object.isRequired 105 | }; 106 | 107 | export default withStyles(styles)(Chips); -------------------------------------------------------------------------------- /front_web/src/components/Home.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react'; 2 | 3 | import Post from './Post' 4 | 5 | class Home extends Component { 6 | 7 | constructor(props) { 8 | super(props); 9 | this.state = { 10 | posts: [], 11 | } 12 | } 13 | 14 | componentDidMount = async () => { 15 | let data = await fetch("/get-posts") 16 | let json = await data.json() 17 | if (json.status === 0) { 18 | this.setState({ 19 | posts: json.data.map(item => ( 20 | 27 | )) 28 | }) 29 | } 30 | } 31 | 32 | render() { 33 | return ( 34 |
35 | {this.state.posts} 36 |
37 | ); 38 | } 39 | } 40 | 41 | export default Home; -------------------------------------------------------------------------------- /front_web/src/components/Label.js: -------------------------------------------------------------------------------- 1 | import React, {Component} from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import {withStyles} from '@material-ui/core/styles'; 4 | import Chip from '@material-ui/core/Chip'; 5 | 6 | import ShowPosts from './ShowPosts' 7 | import Post from './Post' 8 | 9 | const styles = theme => ({ 10 | root: { 11 | display: 'flex', 12 | justifyContent: 'center', 13 | flexWrap: 'wrap', 14 | margin: '8% 5%' 15 | }, 16 | chip: { 17 | margin: theme.spacing.unit 18 | } 19 | }); 20 | 21 | 22 | class Chips extends Component { 23 | 24 | constructor(props) { 25 | super(props) 26 | this.state = { 27 | chips: [], 28 | tips: "点击标签查看相应文章", 29 | posts: [], 30 | isShow: false, 31 | disable: true, 32 | } 33 | } 34 | 35 | componentDidMount = () => { 36 | fetch('/get-labels') 37 | .then(data => data.json()) 38 | .then(json => { 39 | if (json.status === 0) { 40 | this.renderChip(json.data) 41 | } 42 | }) 43 | .catch(err => console.err("ERROR: ", err)) 44 | } 45 | 46 | handleClick = (id, label) => { 47 | fetch('/get-posts-by-label/' + id) 48 | .then(data => data.json()) 49 | .then(json => { 50 | if (json.status === 0) { 51 | this.setState({ 52 | posts: json.data.map(item => ( 53 | 60 | )), 61 | tips: label, 62 | isShow: true, 63 | disable: false, 64 | }) 65 | } 66 | }) 67 | .catch(err => console.err("ERROR: ", err)) 68 | } 69 | 70 | renderChip = (data) => { 71 | if (Array.isArray(data)) { 72 | this.setState({ 73 | chips: data.map(item => ( 74 | { 80 | this.handleClick(item.Id, item.Label) 81 | }} 82 | /> 83 | )) 84 | }) 85 | } 86 | } 87 | 88 | onChange = () => { 89 | this.setState({ 90 | isShow: !this.state.isShow, 91 | }) 92 | } 93 | 94 | render() { 95 | const {classes} = this.props; 96 | return ( 97 |
98 |
{this.state.chips}
99 | 100 | { this.state.posts} 101 | 102 |
103 | ); 104 | } 105 | } 106 | 107 | Chips.propTypes = { 108 | classes: PropTypes.object.isRequired 109 | }; 110 | 111 | export default withStyles(styles)(Chips); -------------------------------------------------------------------------------- /front_web/src/components/Post.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { withStyles } from '@material-ui/core/styles'; 4 | import Paper from '@material-ui/core/Paper'; 5 | import Typography from '@material-ui/core/Typography'; 6 | import Button from '@material-ui/core/Button'; 7 | import { withRouter } from 'react-router-dom' 8 | 9 | const styles = theme => ({ 10 | root: theme.mixins.gutters({ 11 | width: '100%', 12 | paddingTop: 16, 13 | paddingBottom: 16, 14 | // 15 | }), 16 | button: { 17 | marginTop: theme.spacing.unit * 2, 18 | dispaly: 'block', 19 | width: '100%', 20 | border: 'none', 21 | }, 22 | }); 23 | 24 | function PaperSheet(props) { 25 | const { classes, id, title, date, amount, history} = props; 26 | let postDate = new Date(date * 1000) 27 | postDate = `${postDate.getFullYear()}年${String(postDate.getMonth() + 1).padStart(2, '0')}月${String(postDate.getDate()).padStart(2, '0')}日` 28 | const handleClick = () => { 29 | history.push("/article", {id}) 30 | } 31 | return ( 32 | 45 | ); 46 | } 47 | 48 | PaperSheet.propTypes = { 49 | classes: PropTypes.object.isRequired, 50 | title: PropTypes.string.isRequired, 51 | date: PropTypes.string.isRequired, 52 | amount: PropTypes.string.isRequired, 53 | }; 54 | 55 | export default withRouter(withStyles(styles)(PaperSheet)); -------------------------------------------------------------------------------- /front_web/src/components/ShowPosts.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import PropTypes from 'prop-types'; 3 | import { withStyles } from '@material-ui/core/styles'; 4 | import ExpansionPanel from '@material-ui/core/ExpansionPanel'; 5 | import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary'; 6 | import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails'; 7 | import Typography from '@material-ui/core/Typography'; 8 | import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; 9 | 10 | const styles = theme => ({ 11 | root: { 12 | width: '100%', 13 | }, 14 | heading: { 15 | fontSize: theme.typography.pxToRem(15), 16 | fontWeight: theme.typography.fontWeightRegular, 17 | }, 18 | }); 19 | 20 | function SimpleExpansionPanel(props) { 21 | const { classes, tips, children, isShow, onChange, disable } = props; 22 | return ( 23 |
24 | 25 | }> 26 | {tips} 27 | 28 | 29 | {children} 30 | 31 | 32 |
33 | ); 34 | } 35 | 36 | SimpleExpansionPanel.propTypes = { 37 | classes: PropTypes.object.isRequired, 38 | isShow: PropTypes.bool, 39 | tips: PropTypes.string, 40 | }; 41 | 42 | export default withStyles(styles)(SimpleExpansionPanel); -------------------------------------------------------------------------------- /front_web/src/index.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce-16/my-blog-by-go/38d3e5491d079394a9ce066127c917fe8010ba74/front_web/src/index.css -------------------------------------------------------------------------------- /front_web/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import registerServiceWorker from './registerServiceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | registerServiceWorker(); 9 | -------------------------------------------------------------------------------- /front_web/src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /front_web/src/registerServiceWorker.js: -------------------------------------------------------------------------------- 1 | // In production, we register a service worker to serve assets from local cache. 2 | 3 | // This lets the app load faster on subsequent visits in production, and gives 4 | // it offline capabilities. However, it also means that developers (and users) 5 | // will only see deployed updates on the "N+1" visit to a page, since previously 6 | // cached resources are updated in the background. 7 | 8 | // To learn more about the benefits of this model, read https://goo.gl/KwvDNy. 9 | // This link also includes instructions on opting out of this behavior. 10 | 11 | const isLocalhost = Boolean( 12 | window.location.hostname === 'localhost' || 13 | // [::1] is the IPv6 localhost address. 14 | window.location.hostname === '[::1]' || 15 | // 127.0.0.1/8 is considered localhost for IPv4. 16 | window.location.hostname.match( 17 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 18 | ) 19 | ); 20 | 21 | export default function register() { 22 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 23 | // The URL constructor is available in all browsers that support SW. 24 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location); 25 | if (publicUrl.origin !== window.location.origin) { 26 | // Our service worker won't work if PUBLIC_URL is on a different origin 27 | // from what our page is served on. This might happen if a CDN is used to 28 | // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 29 | return; 30 | } 31 | 32 | window.addEventListener('load', () => { 33 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 34 | 35 | if (isLocalhost) { 36 | // This is running on localhost. Lets check if a service worker still exists or not. 37 | checkValidServiceWorker(swUrl); 38 | 39 | // Add some additional logging to localhost, pointing developers to the 40 | // service worker/PWA documentation. 41 | navigator.serviceWorker.ready.then(() => { 42 | console.log( 43 | 'This web app is being served cache-first by a service ' + 44 | 'worker. To learn more, visit https://goo.gl/SC7cgQ' 45 | ); 46 | }); 47 | } else { 48 | // Is not local host. Just register service worker 49 | registerValidSW(swUrl); 50 | } 51 | }); 52 | } 53 | } 54 | 55 | function registerValidSW(swUrl) { 56 | navigator.serviceWorker 57 | .register(swUrl) 58 | .then(registration => { 59 | registration.onupdatefound = () => { 60 | const installingWorker = registration.installing; 61 | installingWorker.onstatechange = () => { 62 | if (installingWorker.state === 'installed') { 63 | if (navigator.serviceWorker.controller) { 64 | // At this point, the old content will have been purged and 65 | // the fresh content will have been added to the cache. 66 | // It's the perfect time to display a "New content is 67 | // available; please refresh." message in your web app. 68 | console.log('New content is available; please refresh.'); 69 | } else { 70 | // At this point, everything has been precached. 71 | // It's the perfect time to display a 72 | // "Content is cached for offline use." message. 73 | console.log('Content is cached for offline use.'); 74 | } 75 | } 76 | }; 77 | }; 78 | }) 79 | .catch(error => { 80 | console.error('Error during service worker registration:', error); 81 | }); 82 | } 83 | 84 | function checkValidServiceWorker(swUrl) { 85 | // Check if the service worker can be found. If it can't reload the page. 86 | fetch(swUrl) 87 | .then(response => { 88 | // Ensure service worker exists, and that we really are getting a JS file. 89 | if ( 90 | response.status === 404 || 91 | response.headers.get('content-type').indexOf('javascript') === -1 92 | ) { 93 | // No service worker found. Probably a different app. Reload the page. 94 | navigator.serviceWorker.ready.then(registration => { 95 | registration.unregister().then(() => { 96 | window.location.reload(); 97 | }); 98 | }); 99 | } else { 100 | // Service worker found. Proceed as normal. 101 | registerValidSW(swUrl); 102 | } 103 | }) 104 | .catch(() => { 105 | console.log( 106 | 'No internet connection found. App is running in offline mode.' 107 | ); 108 | }); 109 | } 110 | 111 | export function unregister() { 112 | if ('serviceWorker' in navigator) { 113 | navigator.serviceWorker.ready.then(registration => { 114 | registration.unregister(); 115 | }); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /gin.log: -------------------------------------------------------------------------------- 1 | [GIN] 2018/06/11 - 16:48:56 | 200 | 1.9976ms | 127.0.0.1 | GET /get-posts 2 | [GIN] 2018/06/11 - 16:49:02 | 200 | 8.994ms | 127.0.0.1 | GET /get-html-str/33 3 | [GIN] 2018/06/11 - 16:49:05 | 200 | 998.2µs | 127.0.0.1 | GET /get-labels 4 | [GIN] 2018/06/11 - 16:49:06 | 200 | 1.0002ms | 127.0.0.1 | GET /get-posts-by-label/20 5 | [GIN] 2018/06/11 - 16:49:09 | 200 | 1.9933ms | 127.0.0.1 | GET /get-posts 6 | [GIN] 2018/06/11 - 16:53:29 | 404 | 0s | ::1 | POST //upload 7 | [GIN] 2018/06/11 - 16:57:34 | 200 | 529.2834ms | ::1 | POST /upload 8 | [GIN] 2018/06/11 - 16:57:46 | 200 | 0s | 127.0.0.1 | GET /get-posts 9 | [GIN] 2018/06/11 - 16:57:47 | 200 | 1.9976ms | 127.0.0.1 | GET /get-html-str/34 10 | [GIN] 2018/06/11 - 16:57:47 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 11 | [GIN] 2018/06/11 - 16:57:47 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 12 | [GIN] 2018/06/11 - 16:57:47 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 13 | [GIN] 2018/06/11 - 17:04:03 | 200 | 2.9983ms | 127.0.0.1 | GET /get-html-str/34 14 | [GIN] 2018/06/11 - 17:04:03 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 15 | [GIN] 2018/06/11 - 17:04:03 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 16 | [GIN] 2018/06/11 - 17:04:03 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 17 | [GIN] 2018/06/11 - 17:04:41 | 200 | 11.9936ms | 127.0.0.1 | GET /get-html-str/34 18 | [GIN] 2018/06/11 - 17:04:41 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 19 | [GIN] 2018/06/11 - 17:04:41 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 20 | [GIN] 2018/06/11 - 17:04:41 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 21 | [GIN] 2018/06/11 - 17:12:21 | 200 | 984.5µs | 127.0.0.1 | GET /get-html-str/34 22 | [GIN] 2018/06/11 - 17:12:21 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 23 | [GIN] 2018/06/11 - 17:12:21 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 24 | [GIN] 2018/06/11 - 17:12:21 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 25 | [GIN] 2018/06/11 - 17:17:14 | 200 | 1.9989ms | 127.0.0.1 | GET /get-html-str/34 26 | [GIN] 2018/06/11 - 17:17:14 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 27 | [GIN] 2018/06/11 - 17:17:14 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 28 | [GIN] 2018/06/11 - 17:17:14 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 29 | [GIN] 2018/06/11 - 17:17:15 | 200 | 3.9982ms | 127.0.0.1 | GET /get-posts 30 | [GIN] 2018/06/11 - 17:17:17 | 200 | 1.0093ms | 127.0.0.1 | GET /get-posts 31 | [GIN] 2018/06/11 - 17:17:56 | 200 | 0s | 127.0.0.1 | GET /get-html-str/33 32 | [GIN] 2018/06/11 - 17:17:57 | 200 | 2.9987ms | 127.0.0.1 | GET /get-posts 33 | [GIN] 2018/06/11 - 17:17:58 | 200 | 998.2µs | 127.0.0.1 | GET /get-html-str/34 34 | [GIN] 2018/06/11 - 17:17:58 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 35 | [GIN] 2018/06/11 - 17:17:58 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 36 | [GIN] 2018/06/11 - 17:17:58 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 37 | [GIN] 2018/06/11 - 17:18:31 | 200 | 999µs | 127.0.0.1 | GET /get-html-str/34 38 | [GIN] 2018/06/11 - 17:18:31 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 39 | [GIN] 2018/06/11 - 17:18:31 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 40 | [GIN] 2018/06/11 - 17:18:31 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 41 | [GIN] 2018/06/11 - 17:19:23 | 200 | 998.1µs | 127.0.0.1 | GET /get-html-str/34 42 | [GIN] 2018/06/11 - 17:19:23 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 43 | [GIN] 2018/06/11 - 17:19:23 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 44 | [GIN] 2018/06/11 - 17:19:23 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 45 | [GIN] 2018/06/11 - 17:20:08 | 200 | 5.9965ms | 127.0.0.1 | GET /get-html-str/34 46 | [GIN] 2018/06/11 - 17:20:08 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 47 | [GIN] 2018/06/11 - 17:20:08 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 48 | [GIN] 2018/06/11 - 17:20:08 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 49 | [GIN] 2018/06/11 - 17:20:56 | 200 | 0s | 127.0.0.1 | GET /get-posts 50 | [GIN] 2018/06/11 - 17:21:06 | 200 | 998.5µs | 127.0.0.1 | GET /get-html-str/33 51 | [GIN] 2018/06/11 - 17:21:11 | 200 | 1.0196ms | 127.0.0.1 | GET /get-posts 52 | [GIN] 2018/06/11 - 17:22:33 | 200 | 997.7µs | 127.0.0.1 | GET /get-posts 53 | [GIN] 2018/06/11 - 17:23:20 | 200 | 999µs | 127.0.0.1 | GET /get-posts 54 | [GIN] 2018/06/11 - 17:24:11 | 200 | 2.9996ms | 127.0.0.1 | GET /get-html-str/33 55 | [GIN] 2018/06/11 - 17:24:12 | 200 | 2.9987ms | 127.0.0.1 | GET /get-posts 56 | [GIN] 2018/06/11 - 17:24:18 | 200 | 1.0071ms | 127.0.0.1 | GET /get-labels 57 | [GIN] 2018/06/11 - 17:24:20 | 200 | 1.0328ms | 127.0.0.1 | GET /get-posts-by-label/23 58 | [GIN] 2018/06/11 - 17:24:21 | 200 | 999µs | 127.0.0.1 | GET /get-posts-by-label/22 59 | [GIN] 2018/06/11 - 17:24:22 | 200 | 1.0003ms | 127.0.0.1 | GET /get-posts-by-label/21 60 | [GIN] 2018/06/11 - 17:24:23 | 200 | 1.998ms | 127.0.0.1 | GET /get-posts-by-label/20 61 | [GIN] 2018/06/11 - 17:24:24 | 200 | 2.9982ms | 127.0.0.1 | GET /get-categoies 62 | [GIN] 2018/06/11 - 17:24:25 | 200 | 1.9997ms | 127.0.0.1 | GET /get-posts-by-category/86 63 | [GIN] 2018/06/11 - 17:24:26 | 200 | 997.3µs | 127.0.0.1 | GET /get-posts-by-category/85 64 | [GIN] 2018/06/11 - 17:24:27 | 200 | 1.002ms | 127.0.0.1 | GET /get-posts-by-category/84 65 | [GIN] 2018/06/11 - 17:24:27 | 200 | 1.9954ms | 127.0.0.1 | GET /get-posts-by-category/83 66 | [GIN] 2018/06/11 - 17:24:27 | 200 | 999.5µs | 127.0.0.1 | GET /get-posts-by-category/82 67 | [GIN] 2018/06/11 - 17:24:28 | 200 | 993µs | 127.0.0.1 | GET /get-labels 68 | [GIN] 2018/06/11 - 17:24:32 | 200 | 999.4µs | 127.0.0.1 | GET /get-posts 69 | [GIN] 2018/06/11 - 17:28:26 | 200 | 248.855ms | ::1 | POST /upload 70 | [GIN] 2018/06/11 - 17:28:31 | 200 | 0s | 127.0.0.1 | GET /get-posts 71 | [GIN] 2018/06/11 - 17:28:33 | 200 | 1.998ms | 127.0.0.1 | GET /get-html-str/35 72 | [GIN] 2018/06/11 - 17:28:33 | 404 | 0s | 127.0.0.1 | GET /uploads/ganbadie.jpg 73 | [GIN] 2018/06/11 - 17:28:47 | 200 | 0s | 127.0.0.1 | GET /get-posts 74 | [GIN] 2018/06/11 - 17:33:53 | 200 | 2.997ms | 127.0.0.1 | GET /get-html-str/34 75 | [GIN] 2018/06/11 - 17:33:53 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/1.png 76 | [GIN] 2018/06/11 - 17:33:53 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/2.png 77 | [GIN] 2018/06/11 - 17:33:53 | 404 | 0s | 127.0.0.1 | GET /uploads/post/Go中的切片-1/3.png 78 | [GIN] 2018/06/11 - 17:35:22 | 200 | 997.3µs | 127.0.0.1 | GET /get-labels 79 | [GIN] 2018/06/11 - 17:35:24 | 200 | 1.0067ms | 127.0.0.1 | GET /get-posts-by-label/23 80 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io" 5 | "os" 6 | 7 | "github.com/gin-contrib/cors" 8 | "github.com/gin-gonic/gin" 9 | _ "github.com/mattn/go-sqlite3" 10 | "github.com/zachrey/blog/routers" 11 | ) 12 | 13 | func main() { 14 | r := gin.New() 15 | // 设置跨域 16 | r.Use(cors.Default()) 17 | 18 | // 设置日志文件 19 | f, _ := os.Create("gin.log") 20 | gin.DefaultWriter = io.MultiWriter(f, os.Stdout) 21 | // 使用日志中间件 22 | r.Use(gin.Logger()) 23 | // 设置静态文件夹 24 | r.Static("/static", "./static") 25 | // 加载路由 26 | routers.LoadRouters(r) 27 | r.Run(":8888") 28 | } 29 | -------------------------------------------------------------------------------- /models/category.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "log" 5 | "regexp" 6 | 7 | db "github.com/zachrey/blog/database" 8 | ) 9 | 10 | type MCategory struct { 11 | Id int64 `xorm:"pk autoincr"` 12 | Category string `xorm:"unique 'category'"` 13 | CreateTime int64 `xorm:"created 'create_time'"` 14 | } 15 | 16 | // GetLabels 获取所有的标签 17 | func GetCategories() *[]MCategory { 18 | var categories []MCategory 19 | err := db.ORM.Table("categories").Find(&categories) 20 | if err != nil { 21 | log.Println("ERROR:", err) 22 | return nil 23 | } 24 | return &categories 25 | } 26 | 27 | func InsertCategory(categories string, ch chan []int64) { 28 | categoriesArr := regexp.MustCompile(`\s*,\s*`).Split(categories, -1) 29 | ids := make([]int64, len(categoriesArr)) 30 | for i, v := range categoriesArr { 31 | newCategories := &MCategory{Category: v} 32 | db.ORM.Table("categories").Insert(newCategories) 33 | if newCategories.Id == 0 { 34 | var newCategories2 MCategory 35 | db.ORM.Table("categories").Where("categories.category=?", v).Get(&newCategories2) 36 | ids[i] = newCategories2.Id 37 | } else { 38 | ids[i] = newCategories.Id 39 | } 40 | } 41 | ch <- ids 42 | } 43 | -------------------------------------------------------------------------------- /models/label.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "log" 5 | "regexp" 6 | 7 | db "github.com/zachrey/blog/database" 8 | ) 9 | 10 | type MLabel struct { 11 | Id int64 `xorm:"pk autoincr"` 12 | Label string `xorm:"unique 'label'"` 13 | CreateTime int64 `xorm:"created 'create_time'"` 14 | } 15 | 16 | // GetLabels 获取所有的标签 17 | func GetLabels() *[]MLabel { 18 | var labels []MLabel 19 | err := db.ORM.Table("labels").Find(&labels) 20 | if err != nil { 21 | log.Println("ERROR:", err) 22 | return nil 23 | } 24 | return &labels 25 | } 26 | 27 | func InsertLabel(labels string, ch chan []int64) { 28 | labelsArr := regexp.MustCompile(`\s*,\s*`).Split(labels, -1) 29 | ids := make([]int64, len(labelsArr)) 30 | for i, v := range labelsArr { 31 | newLabel := &MLabel{Label: v} 32 | db.ORM.Table("labels").Insert(newLabel) 33 | if newLabel.Id == 0 { 34 | var newLabel2 MLabel 35 | db.ORM.Table("labels").Where("labels.label=?", v).Get(&newLabel2) 36 | ids[i] = newLabel2.Id 37 | } else { 38 | ids[i] = newLabel.Id 39 | } 40 | } 41 | ch <- ids 42 | } 43 | -------------------------------------------------------------------------------- /models/post.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "database/sql" 5 | "log" 6 | 7 | db "github.com/zachrey/blog/database" 8 | ) 9 | 10 | type MPost struct { 11 | Id int64 `xorm:"pk autoincr"` 12 | Title string `xorm:"'title'"` 13 | FileName string `xorm: "file_name"` 14 | TextAmount int64 `xorm: "text_amount"` 15 | CreateTime int64 `xorm:"created 'create_time'"` 16 | } 17 | 18 | // GetPostByID 根据ID获取文章 19 | func GetPostByID(Id int64) *MPost { 20 | var post MPost 21 | has, err := db.ORM.Table("posts").Id(Id).Get(&post) 22 | if err != nil { 23 | log.Println("ERROR:", err) 24 | return nil 25 | } 26 | if has == false { 27 | return nil 28 | } 29 | return &post 30 | } 31 | 32 | // GetPostByTitle 根据标题获取post 33 | func GetPostByTitle(title string) *MPost { 34 | var post MPost 35 | has, err := db.ORM.Table("posts").Where("title=?", title).Get(&post) 36 | if err != nil { 37 | log.Println("ERROR:", err) 38 | return nil 39 | } 40 | if has == false { 41 | return nil 42 | } 43 | return &post 44 | } 45 | 46 | // GetPosts 获取所有的文章 47 | func GetPosts() *[]MPost { 48 | var post []MPost 49 | err := db.ORM.Table("posts").Find(&post) 50 | if err != nil { 51 | log.Println("ERROR:", err) 52 | return nil 53 | } 54 | return &post 55 | } 56 | 57 | // InsertPost 将标题插入到posts表 58 | func InsertPost(title, fileName string, textAmount int64, ch chan int64) { 59 | newPost := new(MPost) 60 | newPost.Title = title 61 | newPost.FileName = fileName 62 | newPost.TextAmount = textAmount 63 | db.ORM.Table("posts").Insert(newPost) 64 | ch <- newPost.Id 65 | } 66 | 67 | // RemovePostByID 根据ID删除post 68 | func RemovePostByID(ID int64) (sql.Result, error) { 69 | sql := "DELETE FROM posts WHERE id=?" 70 | affacted, err := db.ORM.Sql(sql, ID).Execute() 71 | return affacted, err 72 | } 73 | -------------------------------------------------------------------------------- /models/post_category.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "database/sql" 5 | "log" 6 | 7 | db "github.com/zachrey/blog/database" 8 | ) 9 | 10 | type MPostAndCategory struct { 11 | Id int64 `xorm:"pk autoincr"` 12 | PostId int64 `xorm:"'post_id'"` 13 | CategoryId int64 `xorm:"'category_id'"` 14 | CreateTime int64 `xorm:"created 'create_time'"` 15 | } 16 | 17 | type MCategoryAndPost struct { 18 | CategoryId int64 `xorm:"'category_id'"` 19 | PostId int64 `xorm:"'post_id'"` 20 | MPost `xorm:"extends"` 21 | } 22 | 23 | // InsertPostAndCategory 将标题插入到post_category表 24 | func InsertPostAndCategory(PostId, CategoryId int64) (int64, error) { 25 | mPostAndCategory := &MPostAndCategory{ 26 | PostId: PostId, 27 | CategoryId: CategoryId, 28 | } 29 | _, err := db.ORM.Table("post_category").Insert(mPostAndCategory) 30 | return mPostAndCategory.Id, err 31 | } 32 | 33 | // GetPostsByPLId 根据该表里面的id 34 | func GetPostsByPCId(categoryId int64) *[]MCategoryAndPost { 35 | posts := make([]MCategoryAndPost, 0) 36 | err := db.ORM. 37 | Table("post_category"). 38 | Join("INNER", "posts", "post_category.post_id=posts.id"). 39 | Where("post_category.category_id=?", categoryId). 40 | Find(&posts) 41 | if err != nil { 42 | log.Println("ERROR:", err) 43 | return nil 44 | } 45 | return &posts 46 | } 47 | 48 | // RemovePCByPostID 根据postid删除对于的记录 49 | func RemovePCByPostID(postID int64) (sql.Result, error) { 50 | sql := "DELETE FROM post_category WHERE post_id=?" 51 | affacted, err := db.ORM.Sql(sql, postID).Execute() 52 | return affacted, err 53 | } 54 | -------------------------------------------------------------------------------- /models/post_label.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "database/sql" 5 | "log" 6 | 7 | db "github.com/zachrey/blog/database" 8 | ) 9 | 10 | type MPostAndLabel struct { 11 | Id int64 `xorm:"pk autoincr"` 12 | PostId int64 `xorm:"'post_id'"` 13 | LabelId int64 `xorm:"'Label_id'"` 14 | CreateTime int64 `xorm:"created 'create_time'"` 15 | } 16 | 17 | type LabelAndPost struct { 18 | LabelId int64 `xorm:"'label_id'"` 19 | PostId int64 `xorm:"'post_id'"` 20 | MPost `xorm:"extends"` 21 | } 22 | 23 | // InsertPostAndLabel 将标题插入到post_label表 24 | func InsertPostAndLabel(PostId, LabelId int64) (int64, error) { 25 | mPostAndLabel := &MPostAndLabel{ 26 | PostId: PostId, 27 | LabelId: LabelId, 28 | } 29 | _, err := db.ORM.Table("post_label").Insert(mPostAndLabel) 30 | return mPostAndLabel.Id, err 31 | } 32 | 33 | // GetPostsByPLId 根据该表里面的id 34 | func GetPostsByPLId(labelId int64) *[]LabelAndPost { 35 | posts := make([]LabelAndPost, 0) 36 | err := db.ORM. 37 | Table("post_label"). 38 | Join("INNER", "posts", "post_label.post_id=posts.id"). 39 | Where("post_label.label_id=?", labelId). 40 | Find(&posts) 41 | if err != nil { 42 | log.Println("ERROR:", err) 43 | return nil 44 | } 45 | return &posts 46 | } 47 | 48 | // RemoveByPostID 根据postid删除对于的记录 49 | func RemovePLByPostID(postID int64) (sql.Result, error) { 50 | sql := "DELETE FROM post_label WHERE post_id=?" 51 | affacted, err := db.ORM.Sql(sql, postID).Execute() 52 | return affacted, err 53 | } 54 | -------------------------------------------------------------------------------- /posts/0890fb6686475586ea27ca4833af7533.md: -------------------------------------------------------------------------------- 1 | title: Go中的切片-1 2 | categories: Go, 后端 3 | label: Go, Slice 4 | --------------------------------------------- 5 | 6 | ## 切片的内部实现 7 | 切片是一个很小的对象,对底层数组进行了抽象,并提供相关的操作方法。 8 | 9 | ![](/uploads/post/Go中的切片-1/1.png) 10 | 11 | 12 | 13 | 可以看到切片有三个元数据,一个是指向底层数组头部的指针、一个代表切片的长度、一个代表切片的容量。 14 | 15 | ## 创建切片 16 | ### 使用`make`创建。 17 | ```golang 18 | slice1 := make([]int) // nil 19 | slice2 := make([]int, 5) // {0, 0, 0, 0, 0} 因为int的空值为0 20 | slice3 := make([]int, 5, 10) // {0, 0, 0, 0, 0} 可以增长到10个元素 21 | ``` 22 | 这里看起来`slice2`和`slice3`值的区别不大,但是当谁用`append`方式,容器这个元数据决定,是否新建一个底层数组,下面有具体说的地方。 23 | > **容量小于长度的切片会在编译时报错** 24 | 25 | ### 字面量创建 26 | ```golang 27 | // 创建字符串切片 28 | // 其长度和容量都是 5 个元素 29 | slice := []string{"Red", "Blue", "Green", "Yellow", "Pink"} 30 | // 创建一个整型切片 31 | // 其长度和容量都是 3 个元素 32 | slice := []int{10, 20, 30} 33 | // 创建字符串切片 34 | // 使用空字符串初始化第 100 个元素 35 | slice := []string{99: ""} 36 | ``` 37 | 38 | **如果在创建的时候`[]`写了值,例如`[6]`,这样创建的是数组,而不是切片** 39 | 40 | ## nil 和空切片 41 | 因为切片也是属于指针的,所以它的空值就是`nil` 42 | ```golang 43 | var slice []int 44 | // slice == nil 45 | 46 | var slice1 = []int{} 47 | // slice1 != nil 48 | len(slice1) == 0 // true 49 | ``` 50 | 51 | ## 使用切片创建切片 52 | 53 | ```golang 54 | // 创建一个整型切片 55 | // 其长度和容量都是 5 个元素 56 | slice := []int{10, 20, 30, 40, 50} 57 | // 创建一个新切片 58 | // 其长度为 2 个元素,容量为 4 个元素 59 | newSlice := slice[1:3] 60 | ``` 61 | 执行完代码清单 4-25 中的切片动作后,我们有了两个切片,它们**共享同一段底层数组**,但通过不同的切片会看到底层数组的不同部分(见图 4-12)。 62 | ![](/uploads/post/Go中的切片-1/2.png) 63 | 64 | ## 使用 append 向切片增加元素 65 | ```golang 66 | // 创建一个整型切片 67 | // 其长度和容量都是 5 个元素 68 | slice := []int{10, 20, 30, 40, 50} 69 | // 创建一个新切片 70 | // 其长度为 2 个元素,容量为 4 个元素 71 | newSlice := slice[1:3] 72 | // 使用原有的容量来分配一个新元素 73 | // 将新元素赋值为 60 74 | newSlice = append(newSlice, 60) 75 | ``` 76 | 结果如下 77 | ![](/uploads/post/Go中的切片-1/3.png) 78 | 79 | **注意的地方** 80 | 函数 append 会智能地处理底层数组的容量增长。在切片的容量小于 1000 个元素时,总是会成倍地增加容量。一旦元素个数超过 1000,容量的增长因子会设为1.25,也就是会每次增加 25%的容量。随着语言的演化,这种增长算法可能会有所改变。 81 | 82 | 看如下代码 83 | ```golang 84 | slice := []int{1, 2, 3, 4} 85 | newSlice := append(slice, 5, 6) // 增加两个,因为原来slice的容器只有4,但是这里增加了2个,容量不够了,所以就自动的产生了新的底层数组,新的切片的容量变成了8。 86 | newSlice2 := append(newSlice, 6) // 这里在newSlice的基础上增加一个元素,但是没有超过newSlice的容量8,所以不会产生新的底层数组,newSlice2和newSlice使用同一个底层数组。 87 | 88 | newSlice2[0] = 10 // 观察前两个切片的值 89 | fmt.Println(newSlice2[0]) // 10 90 | fmt.Println(slice[0]) // 1 91 | fmt.Println(newSlice[0]) // 10 92 | ``` 93 | 94 | ## 函数传递 95 | 在函数间传递数组的时候,是复制的数组的值,如果数组过多,就会消耗过多内存,所以数组一般会使用`func(arr *[]int)`指针的形式传递。但是切片区别于数组,它只是一个**指向数组的指针**,所以就算底层数组很大,在函数传递的时候,只会**复制切片**(指针),不会复制底层数组,所以传输效率很高。 96 | 97 | 98 | > 文中部分代码和图片来着[《Go语言实战》](https://book.douban.com/subject/27015617/) 99 | > 100 | > 感谢作者 -------------------------------------------------------------------------------- /posts/IMG_2654.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce-16/my-blog-by-go/38d3e5491d079394a9ce066127c917fe8010ba74/posts/IMG_2654.jpg -------------------------------------------------------------------------------- /posts/b128b7694e4de962e0088bcb1bcb254f.md: -------------------------------------------------------------------------------- 1 | title: 一个博客的名称 2 | categories: 分类1, 分类2, 分类3 3 | label: 标签1, 标签2 4 | --------------------------------------------- 5 | 6 | # 标题 7 | **it's golang** 8 | -------------------------------------------------------------------------------- /posts/d79e7ba593ca7a422b63047859abf480.md: -------------------------------------------------------------------------------- 1 | title: JS中扩展符(spread/rest)的各种表现 2 | categories: javascript 3 | label: JS, ES6 4 | --------------------------------------------- 5 | 6 | 7 |
8 | 每一天都以许下希望开始,以收获经验结束。 9 |
10 | 11 | # 深入 '...' 各种情况下的表现形式 12 | 在js中,合并多个对象是一种很常见的操作,在ES5的时候,没有一种很方便的语法来进行对象的合并。在ES6中引入了一个对象函数Object.assgin(source, [target]),再之后又引入了**对象的spread语法**。 13 | 14 | 15 | 16 | 如下: 17 | ```javascript 18 | const cat = { 19 | legs: 4, 20 | sound: 'meow', 21 | }; 22 | const dog = { 23 | ...cat, 24 | sound: 'woof' 25 | }; 26 | 27 | /* 最后结果 28 | dog => { 29 | legs: 4, 30 | sound: 'woof', 31 | } 32 | */ 33 | ``` 34 | 35 | ## spread与属性的可枚举配置 36 | 在ES5及之后的规范中,对象的每一个属性都存在几个来描述该属性的属性。这些值用来描述对象的属性是否可写、可枚举和可配置的状态。这里只说可枚举属性,可枚举属性是一个bool值,代表对象属性是否可以被访问。我们可以使用`Object.keys()`来访问**自己的和可枚举属性**,也可以使用`for...in`语句来**遍历所有可枚举的属性** 37 | 如下: 38 | ```javascript 39 | const person = { 40 | name: 'zachrey', 41 | age: 21, 42 | }; 43 | Object.keys(person); // ['name', 'age'] 44 | console.log({...person}); 45 | /* 46 | { 47 | name: 'zachrey', 48 | age: 21, 49 | } 50 | */ 51 | ``` 52 | 所以`name` `age`是`person`对象中的可枚举属性,目前来说spread可以克隆所有的可枚举属性。 53 | 现在我们来给`person`定义一个不可以枚举的属性,再使用spread看能不能克隆出来。 54 | ```javascript 55 | Object.defineProperty(person, 'sex', { 56 | enumerable: false, 57 | value: 'male', 58 | }); 59 | console.log(person['sex']);// male 60 | 61 | const clonePerson = { 62 | ...person, 63 | }; 64 | console.log(Object.keys(person));// ['name', 'age'] 65 | console.log(clonePerson); 66 | /* 67 | { 68 | name: 'zachrey', 69 | age: 21, 70 | } 71 | */ 72 | ``` 73 | 通过以上可以看出来: 74 | 1. 不可枚举属性,可以被访问,使用`console.log`打印出来。 75 | 2. `...`**并不能克隆**不可枚举属性。 76 | 3. `...`的表现形式与`Object.keys`的表现形式相同。 77 | 78 | ## spread与自身属性 79 | 对于一个js对象,它的属性可以是自己的也可能是原型链上的,接下来简单的实现以下继承。 80 | ```javascript 81 | const personB = Object.create(person, { 82 | profession: { 83 | value: 'development', 84 | enumerable: true, 85 | } 86 | }); 87 | console.log(personB.hasOwnProperty('profession')); // => true 88 | console.log(personB.hasOwnProperty('name')); // => false 89 | console.log(personB.hasOwnProperty('age')); // => false 90 | ``` 91 | 如上,只有`profession`是属于`personB`自身的。 92 | **Object spread从自己的源属性中进行复制的时候,会忽略继承的属性。** 93 | 如下: 94 | ```javascript 95 | const cloneB = { ...personB }; 96 | console.log(cloneB); // => { profession: 'development' } 97 | ``` 98 | > Object spread可以从源对象中复制自己的和可枚举的属性。和Object.keys()相同。 99 | 100 | ## Object spread规则:最后属性获胜 101 | *** 后者扩展属性覆盖具有相同键的早期属性 *** 102 | 如下: 103 | ```javascript 104 | const cat = { 105 | sound: 'meow', 106 | legs: 4, 107 | }; 108 | 109 | const dog = { 110 | ...cat, 111 | ...{ 112 | sound: 'woof' // <----- 覆盖 cat.sound 113 | } 114 | }; 115 | console.log(dog); // => { sound: 'woof', legs: 4 } 116 | 117 | const anotherDog = { 118 | ...cat, 119 | sound: 'woof' // <---- Overwrites cat.sound 120 | }; 121 | console.log(anotherDog); // => { sound: 'woof', legs: 4 } 122 | ``` 123 | ## 浅拷贝 124 | spread对值是复合类型的属性,只会拷贝它对该值得应用。 125 | 如下: 126 | ```javascript 127 | 128 | const laptop = { 129 | name: 'MacBook Pro', 130 | screen: { size: 17, isRetina: true } 131 | }; 132 | const laptopClone = { ...laptop }; 133 | console.log(laptop === laptopClone); // => false 134 | console.log(laptop.screen === laptopClone.screen); // => true 135 | ``` 136 | 首先比较`laptop === laptopClone`,其值是false。主对象被正确克隆。 137 | 138 | 然而,`laptop.screen === laptopClone.screen`值是true。这意味着,`laptop.screen`和`laptopClone.screen`引用相同的嵌套对象,但没有复制。 139 | 140 | ## 原型丢失 141 | 142 | 这里先声明一个类: 143 | ```javascript 144 | class Game { 145 | constructor(name) { 146 | this.name = name; 147 | } 148 | getMessage() { 149 | return `I like ${this.name}!`; 150 | } 151 | } 152 | const doom = new Game('Doom'); 153 | console.log(doom instanceof Game); // => true console.log(doom.name); // => "Doom" 154 | console.log(doom.getMessage()); // => "I like Doom!" 155 | ``` 156 | 接下来我们使用spread克隆调用构造函数创建的`doom`实例: 157 | ```javascript 158 | const doomClone = { ...doom }; 159 | console.log(doomClone instanceof Game); // => false 160 | console.log(doomClone.name); // => "Doom" 161 | console.log(doomClone.getMessage()); // => TypeError: doomClone.getMessage is not a function 162 | ``` 163 | `...doom`只将自己的属性name复制到`doomClone`而已。doomClone是一个普通的JavaScript对象,其原型是`Object.prototype`,而不是`Game.prototype`,这是可以预期的。Object Spread**不保存源对象的原型**。 164 | 想要修复原型可以使用`Object.setPrototypeOf(doomClone, Game.prototype)`。 165 | 使用Object.assign()可以更合理的克隆doom: 166 | ```javascript 167 | const doomFullClone = Object.assign(new Game(), doom); 168 | console.log(doomFullClone instanceof Game); // => true 169 | console.log(doomFullClone.name); // => "Doom" 170 | console.log(doomFullClone.getMessage()); // => "I like Doom!" 171 | ``` 172 | 173 | ## 传播undefined、null和基本类型 174 | ```javascript 175 | const nothing = undefined; 176 | const missingObject = null; 177 | const two = 2; 178 | console.log({ ...nothing }); // => { } 179 | console.log({ ...missingObject }); // => { } 180 | console.log({ ...two }); // => { } 181 | ``` 182 | 183 | ## 总结 184 | 185 | Object spread有一些规则要记住: 186 | 187 | * 它从源对象中提取自己的和可枚举的属性 188 | * 扩展的属性具有相同键的,后者会覆盖前者 189 | 190 | 与此同时,Object spread是简短而且富有表现力的,同时在嵌套对象上也能很好的工作,同时也保持更新的不变性。它可以轻松的实现对象克隆、合并和填充默认属性。 191 | 192 | 在结构性赋值中使用Object rest语法,可以收集剩余的属性。 193 | 194 | 实际上,Object rest和Object spread是JavaScript的重要补充。 195 | 196 | >[原文链接](https://www.w3cplus.com/javascript/how-three-dots-changed-javascript-object-rest-spread-properties.html "原文链接") 197 | 198 | !['干巴爹'](/uploads/ganbadie.jpg) -------------------------------------------------------------------------------- /routers/router.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | 7 | "github.com/gin-gonic/gin" 8 | ctrs "github.com/zachrey/blog/controllers" 9 | "github.com/zachrey/blog/models" 10 | ) 11 | 12 | // LoadRouters 初始化router 13 | func LoadRouters(router *gin.Engine) { 14 | loadRouters(router) 15 | } 16 | 17 | func loadRouters(router *gin.Engine) { 18 | 19 | router.GET("/", func(c *gin.Context) { 20 | post := models.GetPostByID(1) 21 | log.Println("@@ post", post) 22 | c.JSON(http.StatusOK, gin.H{ 23 | "Status": 0, 24 | "data": post, 25 | }) 26 | }) 27 | 28 | router.POST("/upload", ctrs.UpLoadFile) 29 | router.GET("/remove", ctrs.RemoveFile) 30 | 31 | router.GET("/get-html-str/:postid", ctrs.GetHtmlStr) 32 | 33 | router.GET("/get-labels", ctrs.GetLabels) 34 | router.GET("/get-posts", ctrs.GetPosts) 35 | router.GET("/get-categoies", ctrs.GetCategoies) 36 | router.GET("/get-posts-by-label/:labelid", ctrs.GetPostByLabelId) 37 | router.GET("/get-posts-by-category/:categoryid", ctrs.GetPostByCategoryId) 38 | } 39 | -------------------------------------------------------------------------------- /static/IMG_2654.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce-16/my-blog-by-go/38d3e5491d079394a9ce066127c917fe8010ba74/static/IMG_2654.jpg -------------------------------------------------------------------------------- /static/photo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bruce-16/my-blog-by-go/38d3e5491d079394a9ce066127c917fe8010ba74/static/photo.png -------------------------------------------------------------------------------- /vendor/vendor.json: -------------------------------------------------------------------------------- 1 | { 2 | "comment": "", 3 | "ignore": "test", 4 | "package": [], 5 | "rootPath": "github.com/zachrey/blog" 6 | } 7 | --------------------------------------------------------------------------------