Golang에서 기본 macOS 응용 프로그램을 만들고 반응하는 방법완전한 코드 보호가 있는 js-1부분
소개
'어떻게'시리즈의 다음 문장을 읽는 것을 환영합니다!이번에는 Apple macOS를 위해 이 데스크톱 프로그램을 만드는 과정을 분석하고 Golang 코드를 작성하여 반응할 것입니다.js, 복제 보호가 있습니다.
우리는 마법이 없는 상황에서 이 점을 시도할 것이다!😉
문장 부분
✅ Part 1: Third-party Go package manager
🕓 제2부분: 새로운 바둑 방식과 바둑 모듈
From author: this article (originally) was written about half-year ago, therefore I use
dep
package manager for Go. I'm preparing Part 2 of this article for modern coding with Go Modules.
본 조항의 목적
작업 환경
v1.12.5
v12.3.1
운영 체제
darwin/amd64
패키지 및 종속성 관리자
v0.5.3
(Go)v6.9.0
(Node.js)사용된 패키지
가다
net/http
- 웹 서버를 만드는 데 사용되는 표준 패키지godocgobuffalo/packr
- 필요한 모든 소스를 실행 가능한 바이너리 파일에 패키지로 패키지화(GitHubzserge/webview
- 기본 운영 체제 창에 내장된 브라우저가 있는 플랫폼 간 소프트웨어 패키지GitHub노드회사 명
facebook/create-react-app
-macOS 어플리케이션의 전면(GitHubaxios/axios
- AJAX 요청을 보다 쉽게 작성하기 위해GitHub이론적 기초
현재 발생하고 있는 일을 더욱 잘 이해하기 위해서, 나는 당신이 우리가 의존하고 사용할 소프트웨어 패키지의 업무를 검사하는 것을 건의합니다.
네트워크/http
HTTP 클라이언트와 서버에서 실행되는 패키지를 제공합니다.표준 Go 제공에 포함되며 별도의 설치 및 구성이 필요하지 않습니다.
이것은 우리에게 매우 흥미롭다. 왜냐하면 그것은 이해하기 쉽고 좋은 문서와 기능이 있기 때문이다
http.FileServer()
.자세한 내용은 official documentation 을 참조하십시오.
http。파일 서버()
이 기능은 웹 서버가 지정한 폴더와 모든 파일에 완전히 접근할 수 있도록 하는 것이 관건이다.즉,
http.FileServer()
함수는 웹 서버의 지정한 주소 (루트) 에 폴더를 불러올 수 있도록 합니다.예를 들어, 루트 폴더
./static/images/photos
를 마운트하여 http://localhost:8000/photos
에서 사용할 수 있도록 합니다.http.Handle("/photos", http.FileServer("./static/images/photos"))
고브팔로/파크
대화 제목이 있는 패키지입니다.그는 우리가 필요한 모든 파일을 바이너리 파일로 포장하는 것을 허락했다.
Please note: we are working with the
packr
v1 branch.
다음과 같은 프로젝트 디렉토리 구조가 있다고 가정합니다.
$ tree .
.
├── main.go
└── templates
├── admin
│ └── index.html
└── index.html
파일./main.go
에는 다음이 포함됩니다.package main
import (
"fmt"
"log"
"github.com/gobuffalo/packr"
)
func main() {
// Folder with templates that are needed
// to add to binary file
box := packr.NewBox("./templates")
// Search file inside folder
s, err := box.FindString("amdin/index.html")
if err != nil {
log.Fatal(err)
}
fmt.Println(s)
}
이제 이 항목을 실행 가능한 바이너리 파일로 컴파일합시다.또한 packr 패키지는 ./templates
폴더의 모든 내용을 포장합니다.$ packr build ./main.go
현재 사용 중인 운영 체제나 아키텍처 대신 운영 체제나 아키텍처에 바이너리 파일을 만들려면 다음과 같이 호출할 수 있습니다 packr
.$ GOOS=linux GOARCH=amd64 packr build ./main.go
zserge/webview
현대 그래픽 인터페이스를 만드는 데 사용되는 마이크로 크로스플랫폼 웹 탐색 패키지입니다.
Please note: the article describes how to work with
v0.1.0
.
파일
./main.go
에는 다음이 포함됩니다.package main
import "github.com/zserge/webview"
func main() {
// Open Google into a desktop webview window,
// 1024x768 px, without resize
webview.Open("Google", "https://google.com", 1024, 768, false)
}
프로젝트 구조
$ tree .
.
├── vendor
├── ui
│ ├── build
│ ├── node_modules
│ ├── public
│ ├── src
│ ├── package-lock.json
│ └── package.json
├── helloworld.app
├── Gopkg.lock
├── Gopkg.lock
├── Makefile
└── main.go
기본 파일 및 폴더에 대한 설명vendor
- dep로 설치된 모든 패키지가 여기에 저장됩니다ui
- React가 있는 폴더입니다.js 응용 프로그램(전단)ui/build
- 생성된 React App 운영 버전이 있는 폴더ui/src
- React 응용 프로그램 소스 코드가 포함된 폴더ui/package.json
- 종속성 파일npm
helloworld.app
-macOS 어플리케이션(전용 폴더)Gopkg.toml
- 종속성 파일dep
Makefile
- 애플리케이션 구축을 위한 스크립트 작성main.go
-Golang 애플리케이션 소스 코드(백엔드)코드 작성
충분한 이론.그가 말한 바와 같이 조금도 과장하지 않고 말하자면, 우리 시대의 가장 위대한 프로그래머 중의 하나Linus Torvalds:
Talk is cheap. Show me the code.
— Linus Torvalds
이 건의에 따라 코드를 작성합시다.
나는 모든 줄의 코드를 단독으로 분석하지 않을 것이다. 왜냐하면 나는 그것이 군더기이고 그 반대라고 생각하기 때문이다.모든 코드 명세서는 상세한 주석을 제공했다.
"전체 코드" 예시를 찾습니까?
문제 없어!👌 GitHub에서 특별히 만든 저장소:
회사 명 / 예제 - go-react-macos-app-1
예: native macOS app on Go(Golang) 및 React회사 명
git clone
과make
만 있습니다.초보자 비망록/복사 붙여넣기 개발자
Great, when there is a full code listing at the end of the article, right? You can immediately, without reading the text, copy all the program code and see its execution... At this point, I would like to appeal to all readers who do not want to spend time on theory:
Do not mindlessly copy code from the Internet!
This will not help you (in understanding the code and subject of the article), nor the author (in explaining/helping in the comments).
애플리케이션 프런트엔드
반응하다js는 기능이 강하지만 배우기 쉬운 자바스크립트 라이브러리로 사용자 인터페이스를 만드는 데 사용되며 우리가 응용 프로그램의 앞부분을 실현하는 데 매우 적합하다.
Please note: For this article, we will not use anything but the standard React.js page.
현대의 모든 것처럼, 우리는 React를 설치하는 것부터 시작한다.js와 필요한 모든 보조 라이브러리.
./ui
디렉토리의 js:$ npx create-react-app ui
$ cd ui && npm start && open http://localhost:3000
Ctrl+C
및 설치axios
라이브러리:$ npm i --save axios
./ui/src/App.js
파일의 소스 코드:// Import React and React Hooks
import React, { useState, useEffect } from "react";
// Import axios
import axios from "axios";
// Import logo and CSS
import logo from "./logo.svg";
import "./App.css";
function App() {
// Define storage for data
const [state, setState] = useState([]);
// Retrieving data from an AJAX request.
// Remember that the function passed to useEffect will run,
// after render is fixed on the screen.
// See https://reactjs.org/docs/hooks-reference.html#useeffect
useEffect(() => {
axios
.get("/hello") // GET request to URL /hello
.then(resp => setState(resp.data)) // save response to state
.catch(err => console.log(err)); // catch error
});
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Hello, {state.text}!</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
애플리케이션 백엔드
$ dep ensure -add github.com/gobuffalo/packr
$ dep ensure -add github.com/zserge/webview
$GOPATH/bin/packr
콘솔에서 호출할 수 있습니다.$ go get -u github.com/gobuffalo/packr/packr
./main.go
파일의 소스 코드:package main
import (
"encoding/json"
"net/http"
"github.com/gobuffalo/packr"
"github.com/zserge/webview"
)
// Message : struct for message
type Message struct {
Text string `json:"text"`
}
func main() {
// Bind folder path for packaging with Packr
folder := packr.NewBox("./ui/build")
// Handle to ./static/build folder on root path
http.Handle("/", http.FileServer(folder))
// Handle to showMessage func on /hello path
http.HandleFunc("/hello", showMessage)
// Run server at port 8000 as goroutine
// for non-block working
go http.ListenAndServe(":8000", nil)
// Let's open window app with:
// - name: Golang App
// - address: http://localhost:8000
// - sizes: 800x600 px
// - resizable: true
webview.Open("Golang App", "http://localhost:8000", 800, 600, true)
}
func showMessage(w http.ResponseWriter, r *http.Request) {
// Create Message JSON data
message := Message{"World"}
// Return JSON encoding to output
output, err := json.Marshal(message)
// Catch error, if it happens
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Set header Content-Type
w.Header().Set("Content-Type", "application/json")
// Write output
w.Write(output)
}
기본 macOS 응용 프로그램 구축🏗
$ mkdir -p helloworld.app/Contents/MacOS
./main.go
응용 프로그램 폴더:$ go build -o helloworld.app/Contents/MacOS/helloworld
$ open helloworld.app
Windows와 GNU/Linux의 상호 번역
본고에서 제시한 이론 블록과 코드는 다른 운영체제를 위한 유사한 응용 프로그램 개발과 관련이 있다.이런 상황에서 코드는 변하지 않는다.
Write the code once — run everywhere!
이것은 크로스 시스템의 성질 때문이다.
.exe
.app
내의 바이너리 파일우리는 아래의 문장에서 이것에 대해 연구를 진행할 것이다.
Stay tuned, comment and write only good code!
고정 재료
이 글은 여기서 끝냅니다.지금 너는 8분 전보다 훨씬 많이 알고 있다.
내 축하 받아!🎉
10-15분간 분리하여 읽은 텍스트를 메모리로 복구하고 글에서 코드를 학습합니다.다음은 재료를 더욱 공고히 하기 위해 질문에 대답하고 연습을 해 보자.
네, 물어봐도 돼요. 하지만 전제 조건은 기억이 안 나요.
문제
net/http
의 기능은 무엇입니까?encoding/json
의 봉인 함수는 무엇입니까?연습
goroutine
함수(packr build ./main.go
로 테스트를 작성합니다.showMessage()
.포토 맨
[제목] Jantine Doornboshttps://unsplash.com/photos/HvYy5SEefC8
[1] 말https://unsplash.com/photos/WiONHd_zYI4
[2] 페변 그로스https://unsplash.com/photos/XMFZqrGyV-Q
[3] 프리실라 두프리즈https://unsplash.com/photos/XkKCui44iM0
[프레젠테이션] 빅 쇼스타크 (글쓴이)
붓을 대다.
만약 당신이 이 블로그에 이런 글을 더 많이 발표하고 싶다면, 아래에 논평을 발표하고 구독해 주십시오.감사합니다.😘
물론, 너는 LiberaPay 기부금으로 나를 지지할 수 있다.모든 기부금은 새로운 글을 작성하고 지역 사회를 위한 비영리 개원 프로젝트에 쓰일 것이다.
Reference
이 문제에 관하여(Golang에서 기본 macOS 응용 프로그램을 만들고 반응하는 방법완전한 코드 보호가 있는 js-1부분), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/koddr/how-to-create-a-native-macos-app-on-go-golang-and-react-js-with-full-code-protection-part-1-463k텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)